我有点困惑这段代码是如何工作的:

fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()

在这种情况下,无花果轴是如何工作的?它能做什么?

还有,为什么这不能做同样的事情:

fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)

当前回答

您可能会对这样一个事实感兴趣,即在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()

其他回答

你可以使用以下语句:

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。

依次遍历所有子图:

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])

另一个简洁的解决方案是:

// 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调用中解包坐标轴 并设置是否要在子图之间共享x轴和y轴

是这样的:

import matplotlib.pyplot as plt
# fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
ax1, ax2, ax3, ax4 = axes.flatten()

ax1.plot(range(10), 'r')
ax2.plot(range(10), 'b')
ax3.plot(range(10), 'g')
ax4.plot(range(10), 'k')
plt.show()

这里有一个简单的解决办法

fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=False)
for sp in fig.axes:
    sp.plot(range(10))