Matplotlib添加子图时,奇数数量的图形。

5
我知道add_subplot()可以创建一个方形的图表网格,我正在使用4x4的网格,但是我需要多一个。如何使用奇数个数据点来完成同样的操作并使其看起来像这样?odd grid
3个回答

6
您需要使用gridspec子模块:
fig = pyplot.figure(figsize=(6, 4))
gs = gridspec.GridSpec(nrows=6, ncols=2)

ax11 = fig.add_subplot(gs[:2, 0])
ax21 = fig.add_subplot(gs[2:4, 0])
ax31 = fig.add_subplot(gs[4:, 0])
ax12 = fig.add_subplot(gs[:3, 1])
ax22 = fig.add_subplot(gs[3:, 1])
fig.tight_layout()

enter image description here


5
当然,有非常复杂的解决方案,例如使用gridspec模块,这是许多情况下非常好的工具。
但是,当您有一个相对简单的需求时,仍然可以像往常一样使用add_subplot()
import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = fig.add_subplot(321)
ax2 = fig.add_subplot(323)
ax3 = fig.add_subplot(325)
ax4 = fig.add_subplot(222)
ax5 = fig.add_subplot(224)

图片描述


编辑:为了使轴ax1ax2ax3共享x轴,您可以使用add_subplotsharex参数。可选地,关闭x轴标签应通过将它们设为不可见来完成,否则所有三个轴都将失去标签。

import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = fig.add_subplot(321)
ax2 = fig.add_subplot(323, sharex=ax1)
ax3 = fig.add_subplot(325, sharex=ax1)
ax4 = fig.add_subplot(222)
ax5 = fig.add_subplot(224)

plt.setp(ax1.get_xticklabels(), visible=False)
plt.setp(ax2.get_xticklabels(), visible=False)

我会选择这个答案,因为它的极度简洁。不需要添加比我已经拥有的更多的代码。 - Javier
有没有办法只让左侧的三个子图共享x轴? - Javier
短而精确。 - Javier

2
潜在的选项如下:
fig = plt.figure()                               
ax1 = plt.subplot2grid((6, 2), (0, 0), rowspan=2)
ax2 = plt.subplot2grid((6, 2), (2, 0), rowspan=2)
ax3 = plt.subplot2grid((6, 2), (4, 0), rowspan=2)
ax4 = plt.subplot2grid((6, 2), (0, 1), rowspan=3)
ax5 = plt.subplot2grid((6, 2), (3, 1), rowspan=3)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接