首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在matplotlib中调整每隔一行子图之间的间距

如何在matplotlib中调整每隔一行子图之间的间距
EN

Stack Overflow用户
提问于 2018-08-07 08:19:56
回答 2查看 5.2K关注 0票数 5

我希望在水平方向上调整子图之间的间距。特别是在每隔一行之间。我可以使用fig.subplots_adjust(hspace=n)调整每一行。但是,是否可以将此应用于每2行?

代码语言:javascript
复制
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行之间添加一个空格,并保持其余行不变。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-10 05:42:39

你可以交错两个网格,这样每两个子图之间就有一个更大的间距。

要说明该概念,请执行以下操作:

代码语言:javascript
复制
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()

票数 8
EN

Stack Overflow用户

发布于 2018-08-09 16:20:02

为了避免繁琐的低级处理,比如手动调整轴的位置,我建议使用网格,但只保留一些行为空。

我试过这个:

代码语言:javascript
复制
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比率(两者都必须是整数)来调整与子图相比的空白空间的大小。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51717199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档