How to save this matplotlib metric so that labels on the x axis are not trimmed?

I am using the following code snippet on an ipython laptop using the pandas data analysis library along with 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) 

When the above code is executed, the following (correct) graph is created in the ipython integrated graphics editor:

Correct format

Note that x-lables are displayed correctly.

When an image is saved, however, x-marks are cropped as such:

Erroneous format

I tried calling fig.savefig(savefile, bbox_inches=0 , but to no avail. How can I avoid this trimming?

NOTE. . For your convenience, I have selected the aggregated variable here . This is a dictionary of pandas DataFrame objects, and everything should be necessary to run the above code and reproduce the error (provided that you have pandas v.0.8.1 installed).

Thank you very much in advance!

+4
source share
1 answer

You can use 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') 
+9
source

Source: https://habr.com/ru/post/1434996/


All Articles