Search code examples
pythonpandasmatplotlibxticks

x tick labels in print outside the box when rotated 90 degrees


I'm using a Pandas dataframe to plot a bar graph. The x axis is made up of dates, and I need a lot of x-axis so I rotate them 90 degrees so that they're somewhat readable. However, they're printing outside the box. And even if I try using the figsize, the size of the graph is changed, but still the x ticks are printed outside.

This is the code:

import pandas as pd

df = pd.DataFrame()
df['Date'] = pd.Series(['2023-01-01', '2023-01-02' ,'2023-01-03'])
df['# total dictated'] = pd.Series([45, 32, 22])

ax = df.plot.bar(x='Date', y='# total dictated', rot=90, 
                 title='Total dictations per day', legend=False, fontsize=10, xlabel='')
ax.figure.savefig('volume.png')

And this is the image it gives. Notice how the dates are completely unreadable since they're printed outside the box.

image generated


Solution

  • You need to use bbox_inches = 'tight' in savefig to get it to calculate a tight bounding box. Otherwise the it will use the default savefig.bbox.

    i.e. change the last line to

    ax.figure.savefig('volume.png', bbox_inches = 'tight')