【问题标题】:How to adjust space between every second row of subplots in matplotlib如何调整matplotlib中每第二行子图之间的空间
【发布时间】:2019-01-13 23:28:43
【问题描述】:

我希望水平调整子图之间的空间。特别是在每第二行之间。我可以使用fig.subplots_adjust(hspace=n) 调整每一行。但是是否可以将其应用于每 2 行?

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize = (10,10))
plt.style.use('ggplot')
ax.grid(False)

ax1 = plt.subplot2grid((5,2), (0, 0))
ax2 = plt.subplot2grid((5,2), (0, 1))
ax3 = plt.subplot2grid((5,2), (1, 0))  
ax4 = plt.subplot2grid((5,2), (1, 1))
ax5 = plt.subplot2grid((5,2), (2, 0))
ax6 = plt.subplot2grid((5,2), (2, 1)) 
ax7 = plt.subplot2grid((5,2), (3, 0))
ax8 = plt.subplot2grid((5,2), (3, 1))

fig.subplots_adjust(hspace=0.9)

使用下面的子图,我希望在第 2 行和第 3 行之间添加一个空格,并保持其余部分不变。

【问题讨论】:

  • fig, ax = plt.subplots(figsize = (30,30)) 改变figsize,就是改变你的身材大小。
  • 我在 jupyter notebook 中运行相同的代码,但我只是更改了 figsize 并且效果很好。关于hspace,从官方文档来看,hspace 的目标是按行调整空间,以具有相同的功能,但在每第二行中,您必须根据我的知识寻求定制的东西。
  • 我恢复了编辑,否则它变成了一个完全不同的问题。

标签: python matplotlib plot subplot


【解决方案1】:

您可以将两个网格交错,以便每隔一个子图之间有较大的间距。

为了说明这个概念:

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

n = 3 # number of double-rows
m = 2 # number of columns

t = 0.9 # 1-t == top space 
b = 0.1 # bottom space      (both in figure coordinates)

msp = 0.1 # minor spacing
sp = 0.5  # major spacing

offs=(1+msp)*(t-b)/(2*n+n*msp+(n-1)*sp) # grid offset
hspace = sp+msp+1 #height space per grid

gso = GridSpec(n,m, bottom=b+offs, top=t, hspace=hspace)
gse = GridSpec(n,m, bottom=b, top=t-offs, hspace=hspace)

fig = plt.figure()
axes = []
for i in range(n*m):
    axes.append(fig.add_subplot(gso[i]))
    axes.append(fig.add_subplot(gse[i]))

plt.show()

【讨论】:

  • 感谢@ImportofBeingErnest。我如何将数据分配给特定的subplot?请查看有问题的更新
  • 要绘制数据,您可以使用适当的坐标轴绘图功能。例如。 axes[0].plot([1,2,3]).
【解决方案2】:

不去像手动调整轴的位置那样繁琐的低级技巧,我建议使用网格,但只是将一些行留空。

我试过这个:

import matplotlib.pyplot as plt

plt.figure(figsize=(10., 10.))

num_rows = 6
num_cols = 2

row_height = 3
space_height = 2

num_sep_rows = lambda x: int((x-1)/2)
grid = (row_height*num_rows + space_height*num_sep_rows(num_rows), num_cols)

ax_list = []

for ind_row in range(num_rows):
    for ind_col in range(num_cols):
        grid_row = row_height*ind_row + space_height*num_sep_rows(ind_row+1)
        grid_col = ind_col

        ax_list += [plt.subplot2grid(grid, (grid_row, grid_col), rowspan=row_height)]

plt.subplots_adjust(bottom=.05, top=.95, hspace=.1)

# plot stuff
ax_list[0].plot([0, 1])
ax_list[1].plot([1, 0])
# ...
ax_list[11].plot([0, 1, 4], c='C2')

给出这个结果:

请注意,您可以更改行数;此外,您可以通过调整row_height/space_height 比率(两者都必须是整数)来调整与子图相比空白区域的大小。

【讨论】:

  • 谢谢@cheersmate。这很好,但是如何为每个子图分配不同的输出?
  • 我更新了我的答案,只需使用来自ax_list 的轴并绘制任何你想要的东西。