Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when saving multiple figures to a one multi-page PDF document

I'm trying to save several figures to one multi-page PDF document. My code is as follows:

import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages('output.pdf')

sns.set_style('darkgrid')

g = sns.factorplot(data=df,
                   x='Date',
                   y='Product_Count',
                   col='Company',
                   col_wrap=4,
                   sharey=False)
g.set_xlabels('')
g.set_ylabels('product count')
g.set_xticklabels(rotation=45)
plt.locator_params(axis = 'x', nbins = 8)

f = sns.factorplot(data=df,
                   x='Date',
                   y='Volume_Count',
                   col='Company',
                   col_wrap=4,
                   sharey=False)
f.set_xlabels('')
f.set_ylabels('volume count')
f.set_xticklabels(rotation=45)
plt.locator_params(axis = 'x', nbins = 8)

figures = [g, f]

for figure in figures:
    pdf.savefig(figure)
pdf.close()

I'm seeing this error message:

ValueError: No such figure: <seaborn.axisgrid.FacetGrid object at 0x237CD5F0>

Is there something wrong with the iteration?

like image 336
equanimity Avatar asked Mar 11 '23 04:03

equanimity


1 Answers

g and f are not matplotlib.figure.Figure objects, they are seaborn.axisgrid.FacetGrid objects (as mentioned by @tcaswell in comments).

PdfPages needs the Figure instances, and luckily they are easy to extract from the FacetGrid objects, using g.fig and f.fig.

So, all you need to do is change one line, from

figures = [g, f]

to:

figures = [g.fig, f.fig]
like image 104
tmdavison Avatar answered Mar 14 '23 05:03

tmdavison