繁体   English   中英

在tight_layout之后调整matplotlib子图间距

[英]adjust matplotlib subplot spacing after tight_layout

我想尽量减少图中的空白。 我有一排子图,其中四个图共享其y轴,最后一个图具有单独的轴。 共享轴中间面板没有ylabel或ticklabel。

tight_layout在中间图之间创建了很多空白,好像为刻度标签和ylabel留了空间,但是我宁愿拉伸子图。 这可能吗?

import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

fig = plt.figure()
gs = gridspec.GridSpec(1, 5, width_ratios=[4,1,4,1,2]) 

ax = fig.add_subplot(gs[0])
axes = [ax] + [fig.add_subplot(gs[i], sharey=ax) for i in range(1, 4)]

axes[0].plot(np.random.randint(0,100,100))
barlist=axes[1].bar([1,2],[1,20])

axes[2].plot(np.random.randint(0,100,100))
barlist=axes[3].bar([1,2],[1,20])

axes[0].set_ylabel('data')

axes.append(fig.add_subplot(gs[4]))
axes[4].plot(np.random.randint(0,5,100))
axes[4].set_ylabel('other data')


for ax in axes[1:4]:
    plt.setp(ax.get_yticklabels(), visible=False)


sns.despine();
plt.tight_layout(pad=0, w_pad=0, h_pad=0);

在此处输入图片说明

w_pad = 0设置w_pad = 0不会更改tight_layout的默认设置。 您需要设置类似w_pad = -2 产生下图:

在此处输入图片说明

您可以走得更远,说-3但随后您将开始与上一个情节有一些重叠。

另一种方法是删除plt.tight_layout()并使用自己设置边界

plt.subplots_adjust(left=0.065, right=0.97, top=0.96, bottom=0.065, wspace=0.14)

尽管这可能是一个反复试验的过程。

编辑

通过将刻度线和最后一个图的标签移到右侧,可以获得漂亮的图形。 答案表明您可以使用以下方法完成此操作:

ax.yaxis.tick_right()
ax.yaxis.set_label_position("right") 

因此,对于您的示例:

axes[4].yaxis.tick_right()
axes[4].yaxis.set_label_position("right")

另外,您需要删除sns.despine() 最后,现在无需设置w_pad = -2 ,只需使用plt.tight_layout(pad=0, w_pad=0, h_pad=0)

使用此创建下图:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM