如何在matplotlib中获取多个子块?

2024-04-20 14:08:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我对这段代码的工作方式有点困惑:

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

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

为什么这项工作不能做同样的事情:

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

Tags: 代码show方式fig情况plt事情figure
3条回答

有几种方法可以做到。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()

enter image description here

不过,类似这样的方法也会起作用,但并不是很“干净”,因为您正在创建一个包含子块的图形,然后在子块之上添加:

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

enter image description here

import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)

ax[0, 0].plot(range(10), 'r') #row=0, col=0
ax[1, 0].plot(range(10), 'b') #row=1, col=0
ax[0, 1].plot(range(10), 'g') #row=0, col=1
ax[1, 1].plot(range(10), 'k') #row=1, col=1
plt.show()

enter image description here

  • 也可以在子块调用中解压缩轴

  • 并设置是否要在子块之间共享x和y轴

像这样:

import matplotlib.pyplot as plt
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
ax1.plot(range(10), 'r')
ax2.plot(range(10), 'b')
ax3.plot(range(10), 'g')
ax4.plot(range(10), 'k')
plt.show()

enter image description here

相关问题 更多 >