繁体   English   中英

我怎样才能保存这个 matplotlib 图形,这样 x 轴标签就不会被裁剪掉?

[英]How can I save this matplotlib figure such that the x-axis labels are not cropped out?

我在 ipython notebook 中运行以下代码片段,使用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 标签已正确显示。

然而,当图像被保存时,x 标签被裁剪如下:

格式错误

我试过调用fig.savefig(savefile, bbox_inches=0 ,但无济于事。如何避免这种裁剪?

注意:为了您的方便,我在这里腌制了aggregated变量。 这是pandas DataFrame 对象的字典,它应该是您运行上述代码并重现错误所需的全部内容(假设您安装了pandas v.0.8.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')

暂无
暂无

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

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