【问题标题】:adjust matplotlib subplot spacing after tight_layout在tight_layout 之后调整matplotlib 子图间距
【发布时间】:2017-10-26 06:25:05
【问题描述】:

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

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

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    设置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)
    

    虽然这可能是一个反复试验的过程。

    编辑

    将最后一个绘图的刻度和标签移到右侧可以得到一个漂亮的图表。 This 答案显示您可以通过使用:

    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)就行了

    使用它创建下图:

    【讨论】:

    • 谢谢!这看起来更好,但最后一个 ylabel 已经与倒数第二个面板的条有大量重叠。我希望有办法给最后一个面板更多的水平空间?
    • 这个问题实际上在我的例子中随着更大的字体变得更糟
    • 是的。我不确定你是否可以这样做(至少我不知道我的头顶)。可能有其他人可能知道的重要解决方案。 可能的解决方法是将最后一个图的刻度和标签移动到右侧?
    • @jlarsch 查看我的更新答案以获取另一种可能的解决方案
    • 抱歉让我这么痛苦。我真的很喜欢这个改进的版本,但我希望在所有面板的标记边缘上都有轴线和刻度线。基本上正是我上面情节的美学,但最后一个轴在左边。我曾尝试使用sns.set_style('ticks'),但我无法移除刺,sns.despine() 不断将轴恢复到左侧...
    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多