pythonpandasmatplotlibplotpdfpages

Error when trying to write a matplotlib plot from Pandas DataFrame to pdf


I'm trying to write a plot from matplotlib to a pdf file but getting an error.

I'm creating a plot using matplotlib from a Pandas DataFrame like this:

bplot = dfbuild.plot(x='Build',kind='barh',stacked='True')

From the documentation: http://matplotlib.org/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file

It seems like I should be doing it this way:

from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages(r'c:\temp\page.pdf')
figure = bplot.fig
pp.savefig(figure)
pp.close()

I get this error:

AttributeError: 'AxesSubplot' object has no attribute 'fig'

Solution

  • The problem is that dfbuild.plot returns an AxesSubplot and not a Figure instance, which is required by the savefig function.

    This solves the issue:

    pp.savefig(bplot.figure)