【问题标题】:How can I save this matplotlib figure such that the x-axis labels are not cropped out?如何保存这个 matplotlib 图形,以便不裁剪 x 轴标签?
【发布时间】:2012-09-11 12:32:39
【问题描述】:

我正在 ipython 笔记本中运行以下 sn-p 代码,使用 pandas 数据分析库和 matplotlib.pyplot

titles = {'gradStat_p3': "P3:  Gradiometers", 'magStat_p3': "P3:  Magnetometers",
          'gradStat_mmn': "MMN:  Gradiometers", 'magStat_mmn': "MMN:  Magnetometers"}

scales = {'gradStat': (-2.0 * 1e-22, 3.5 * 1e-22), 'magStat': (-1.6 * 1e-25, 4.5 * 1e-25)}

fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(8, 5))
fig.tight_layout()
for c, component in enumerate(('p3', 'mmn')):
    for s, sensor in enumerate(('gradStat', 'magStat')):
        key = sensor + '_' + component
        axes[c, s].set_ylim(scales[sensor])
        agg = aggregated[key]
        # Plot
        agg.plot(ax=axes[c, s], kind='bar', legend=False, title=titles[key])
        axes[c, s].set_xticklabels(agg.index.format(names=False))
        if not c:  # hide the labels
            axes[c, s].xaxis.set_visible(False)

        saveFile = '/tmp/ERF_comparative_barplot.pdf'
        fig.savefig(saveFile)

执行上述代码时,ipython notebook 的内联图形输出中会生成以下(正确的)绘图:

请注意,x-lable 已正确显示。

然而,当图像被保存时,x-labels 会被这样裁剪:

我曾尝试致电fig.savefig(savefile, bbox_inches=0,但无济于事。如何避免这种裁剪?

注意:为方便起见,我已经腌制了aggregated 变量here。这是 pandas DataFrame 对象的字典,应该是您运行上述代码并重现错误所需的全部内容(假设您安装了 pandas v.0.8.1)。

提前非常感谢!

【问题讨论】:

    标签: python matplotlib pandas


    【解决方案1】:

    您可以使用fig.tight_layout()

    fig, ax = subplots(1,1,1)
    ax.plot(np.random.randn(5))
    ax.set_xticklabels(['this is a very long label', 'b', 'c', 'd', 'e'], rotation=90)
    fig.tight_layout()
    fig.savefig('test.pdf')
    

    【讨论】:

    • 您好!再次感谢!它完美地工作。我真的欠你一杯啤酒,现在……
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2017-08-24
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多