简体   繁体   English

在tight_layout之后调整matplotlib子图间距

[英]adjust matplotlib subplot spacing after tight_layout

I would like to minimize white space in my figure. 我想尽量减少图中的空白。 I have a row of sub plots where four plots share their y-axis and the last plot has a separate axis. 我有一排子图,其中四个图共享其y轴,最后一个图具有单独的轴。 There are no ylabels or ticklabels for the shared axis middle panels. 共享轴中间面板没有ylabel或ticklabel。

tight_layout creates a lot of white space between the the middle plots as if leaving space for tick labels and ylabels but I would rather stretch the sub plots. tight_layout在中间图之间创建了很多空白,好像为刻度标签和ylabel留了空间,但是我宁愿拉伸子图。 Is this possible? 这可能吗?

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);

在此处输入图片说明

Setting w_pad = 0 is not changing the default settings of tight_layout . w_pad = 0设置w_pad = 0不会更改tight_layout的默认设置。 You need to set something like w_pad = -2 . 您需要设置类似w_pad = -2 Which produces the following figure: 产生下图:

在此处输入图片说明

You could go further, to say -3 but then you would start to get some overlap with your last plot. 您可以走得更远,说-3但随后您将开始与上一个情节有一些重叠。

Another way could be to remove plt.tight_layout() and set the boundaries yourself using 另一种方法是删除plt.tight_layout()并使用自己设置边界

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

Though this can be a bit of a trial and error process. 尽管这可能是一个反复试验的过程。

Edit 编辑

A nice looking graph can be achieved by moving the ticks and the labels of the last plot to the right hand side. 通过将刻度线和最后一个图的标签移到右侧,可以获得漂亮的图形。 This answer shows you can do this by using: 答案表明您可以使用以下方法完成此操作:

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

So for your example: 因此,对于您的示例:

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

In addition, you need to remove sns.despine() . 另外,您需要删除sns.despine() Finally, there is now no need to set w_pad = -2 , just use plt.tight_layout(pad=0, w_pad=0, h_pad=0) 最后,现在无需设置w_pad = -2 ,只需使用plt.tight_layout(pad=0, w_pad=0, h_pad=0)

Using this creates the following figure: 使用此创建下图:

在此处输入图片说明

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

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