matplotlib add_subplot奇数个图

时间:2016-12-07 18:54:53

标签: python matplotlib

我知道add_subplot()制作了一个平方的网格网格,我用4x4网格做这个,但我还需要一个。我怎样才能做同样的事情,但是用了奇数个图并使它看起来像这样? odd grid

3 个答案:

答案 0 :(得分:5)

您需要使用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

答案 1 :(得分: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)

enter image description here

<小时/> 编辑:为了使轴ax1ax2ax3共享x轴,您可以使用sharex参数add_subplot。可选地,关闭xlabels应该通过将它们设置为不可见来完成,否则所有三个轴都会松开它们的标签。

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)

答案 2 :(得分:1)

潜在选项如下

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)
相关问题