如何保存此matplotlib图形,以便不裁剪x轴标签?

blz*_*blz 6 python matplotlib pandas

我在ipython笔记本中运行以下代码片段,使用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)
Run Code Online (Sandbox Code Playgroud)

执行上述代码时,在ipython笔记本的内联图形输出中生成以下(正确)图:

格式正确

请注意,正确显示了x-lables.

但是,保存图像时,x标签会被裁剪为:

错误的格式

我试过打电话fig.savefig(savefile, bbox_inches=0,但无济于事.我怎样才能避免这种裁剪?

注意:为方便起见,我在这里腌制aggregated变量.这是一个pandas DataFrame对象的字典,应该只需要运行上面的代码并重现该bug(假设你已经安装了pandas v.0.8.1).

首先十分感谢!

Wou*_*ire 12

你可以使用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')
Run Code Online (Sandbox Code Playgroud)