我有点困惑这段代码是如何工作的:
fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()
在这种情况下,无花果轴是如何工作的?它能做什么?
还有,为什么这不能做同样的事情:
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
我有点困惑这段代码是如何工作的:
fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()
在这种情况下,无花果轴是如何工作的?它能做什么?
还有,为什么这不能做同样的事情:
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
当前回答
阅读文档:matplotlib.pyplot.subplots
Pyplot.subplots()返回一个元组图ax,它使用表示法在两个变量中解包
fig, axes = plt.subplots(nrows=2, ncols=2)
代码:
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
不能工作,因为subplots()是pyplot中的函数,而不是对象图的成员。
其他回答
阅读文档:matplotlib.pyplot.subplots
Pyplot.subplots()返回一个元组图ax,它使用表示法在两个变量中解包
fig, axes = plt.subplots(nrows=2, ncols=2)
代码:
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
不能工作,因为subplots()是pyplot中的函数,而不是对象图的成员。
另一个简洁的解决方案是:
// set up structure of plots
f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20,10))
// for plot 1
ax1.set_title('Title A')
ax1.plot(x, y)
// for plot 2
ax2.set_title('Title B')
ax2.plot(x, y)
// for plot 3
ax3.set_title('Title C')
ax3.plot(x,y)
有几种方法可以做到这一点。subplots方法创建图形和子图,然后存储在ax数组中。例如:
import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig, ax = plt.subplots(nrows=2, ncols=2)
for row in ax:
for col in row:
col.plot(x, y)
plt.show()
然而,像这样的东西也可以工作,虽然它不是那么“干净”,因为你创建了一个带有子图的图形,然后在它们上面添加:
fig = plt.figure()
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, y)
plt.subplot(2, 2, 3)
plt.plot(x, y)
plt.subplot(2, 2, 4)
plt.plot(x, y)
plt.show()
如果你真的想使用循环,请执行以下操作:
def plot(data):
fig = plt.figure(figsize=(100, 100))
for idx, k in enumerate(data.keys(), 1):
x, y = data[k].keys(), data[k].values
plt.subplot(63, 10, idx)
plt.bar(x, y)
plt.show()
您可能会对这样一个事实感兴趣,即在matplotlib 2.1版本中,问题中的第二个代码也可以正常工作。
从更改日志中:
图形类现在有subplots方法 Figure类现在有一个subplots()方法,其行为与pyplot.subplots()相同,但是是在一个现有的图形上。
例子:
import matplotlib.pyplot as plt
fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
plt.show()