我有点困惑这段代码是如何工作的:
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)
当前回答
另一个简洁的解决方案是:
// 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)
其他回答
如果你真的想使用循环,请执行以下操作:
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()
这里有一个简单的解决办法
fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=False)
for sp in fig.axes:
sp.plot(range(10))
您可能会对这样一个事实感兴趣,即在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()
依次遍历所有子图:
fig, axes = plt.subplots(nrows, ncols)
for ax in axes.flatten():
ax.plot(x,y)
访问特定索引:
for row in range(nrows):
for col in range(ncols):
axes[row,col].plot(x[row], y[col])
你可以使用以下语句:
import numpy as np
import matplotlib.pyplot as plt
fig, _ = plt.subplots(nrows=2, ncols=2)
for i, ax in enumerate(fig.axes):
ax.plot(np.sin(np.linspace(0,2*np.pi,100) + np.pi/2*i))
或者用第二个变量plt。次要情节的回报:
fig, ax_mat = plt.subplots(nrows=2, ncols=2)
for i, ax in enumerate(ax_mat.flatten()):
...
Ax_mat是一个轴的矩阵。它的形状是nrows x ncols。