控制matplotlib子图的工作空间
我在想:我有一个 1 行,4 列
的图表。不过,前面三个小图的 y 轴
范围是一样的,也就是说它们表示的是同样的东西。而第四个小图的 y 轴
范围就不一样了。
我想做的是,把前面三个小图之间的 wspace
调整一下,让它们紧挨着在一起(看起来像是一组),然后把第四个小图稍微分开一点,确保它的 y 轴
标签不会重叠。
我可以通过一点 photoshop
编辑轻松做到这一点……但我想要一个代码实现的版本。我该怎么做呢?
1 个回答
12
你可能最想要的是 GridSpec
。它让你可以自由调整子图组之间的 wspace
(宽度间距)。
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
fig = plt.figure()
# create a 1-row 3-column container as the left container
gs_left = gridspec.GridSpec(1, 3)
# create a 1-row 1-column grid as the right container
gs_right = gridspec.GridSpec(1, 1)
# add plots to the nested structure
ax1 = fig.add_subplot(gs_left[0,0])
ax2 = fig.add_subplot(gs_left[0,1])
ax3 = fig.add_subplot(gs_left[0,2])
# create a
ax4 = fig.add_subplot(gs_right[0,0])
# now the plots are on top of each other, we'll have to adjust their edges so that they won't overlap
gs_left.update(right=0.65)
gs_right.update(left=0.7)
# also, we want to get rid of the horizontal spacing in the left gridspec
gs_left.update(wspace=0)
现在我们得到了:
当然,你可能还想处理一下标签等等,但现在你已经有了可调节的间距。
GridSpec
可以用来制作一些相当复杂的布局。你可以看看: