【问题标题】:matplotlib: Remove subplot padding when adding tick labelsmatplotlib:添加刻度标签时删除子图填充
【发布时间】:2015-10-25 13:34:11
【问题描述】:

我有一个问题,即添加刻度标签会干扰我在子图之间给定的填充偏好。我想要的是tight_layout,两者之间根本没有填充,但沿 x 轴有一些自定义刻度。这个 sn-p 和结果图显示了问题:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig_names = ['fig1']
gs = gridspec.GridSpec(1, len(fig_names))
gs.update(hspace=0.0)
figs = dict()

for fig_name in fig_names:
    figs[fig_name] = plt.figure(figsize=(3*len(fig_names),6))
    for i in range(0,len(fig_names)):
        ax = figs[fig_name].add_subplot(gs[i])
        ax.plot([0,1],[0,1], 'r-')
        if i != 0:
            ax.set_yticks(list())
            ax.set_yticklabels(list())
        ax.set_xticks(list())
        ax.set_xticklabels(list())

for name,fig in figs.items():
    fig.text(0.5, 0.03, 'Common xlabel', ha='center', va='center')
    gs.tight_layout(fig, h_pad=0.0, w_pad=0.0)
    ax = fig.add_subplot(gs[len(fig_names)-1])
    ax.legend(('Some plot'), loc=2)

plt.show()

将相应的行改为:

ax.set_xticks([0.5,1.0])
ax.set_xticklabels(['0.5','1.0'])

...不需要的填充被添加到图表中。

无论我输入什么刻度文本,如何自定义刻度文本以使图表没有填充?文本可能与下一个子图“重叠”。

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    也许您可以简单地使用plt.subplots 创建轴:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, axs = plt.subplots(ncols=2, sharey=True)
    for ax in axs:
        ax.plot([0,1],[0,1], 'r-')
        ax.set_xticks([0.5,1.0])
        ax.set_xticklabels(['0.5','1.0'])
    axs[-1].legend(('Some plot'), loc=2)
    for ax in axs[1:]:
        ax.yaxis.set_visible(False)
    fig.subplots_adjust(wspace=0)
    plt.show()
    

    【讨论】:

    • 阁下,您的建议很好。我歌颂你,亲吻你的皇家图章戒指。 (并将此答案标记为已接受)。
    猜你喜欢
    • 2013-06-14
    • 2020-12-16
    • 2020-08-29
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多