Python Pandas and Matplotlib – How can I control the relative size of the figure to text labels?

Question:

Here is a figured produced by Python Pandas + Matplotlib

pandas and matplotlib bar graph

The problem is obvious: The x-axis labels are too large relative to the overall figure size.

There are two ways to solve this:

  • Increase the overall figure size, keeping the label font size the same
  • Reduce the label font size while keeping the figure size the same

I am saving the output as pdf. I would ideally like to use the first option, as when I open this file on my computer, the actual screen rendered size is about 400 pixels wide, which isn’t very large. But this may not be possile when saving as pdf?

The code relevant is just two lines. data_age created from a Pandas dataframe.

    # data is a Panadas dataframe, one of the columns is `'age'`.
    data_age = data['age'].value_counts().sort_index()

    plot = data_age.plot.bar()
    pplt.savefig('age.pdf')

I searched around to find a solution to what I would have assumed would be a commonly encountered problem. I then went and read the documentation for matplotlib. There was an option dpi but this doesn’t seem to have any effect when writing to a pdf file – which isn’t surprising since pdf isn’t a rasterized format.

pplt is obtained from import matplotlib.pyplot as pplt.

Answers:

You should use the ax keyword argument paired with a matplotlib figure. Usage is as follows:

# create a matplotlib figure and set figsize
my_wider_figure, my_ax = plt.subplots(figsize=(15,10))

data_age.plot.bar(ax=my_ax)
Answered By: rsenne
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.