Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

python - Export huge seaborn chart into pdf with multiple pages

I created a program which generates a large number of chart using seaborn catplot. This is the example of my code with the illustration of how the final chart looks like.

plot= sns.catplot(data=df3, x="solutions", y="score", col="subject", col_wrap=3, hue="Value",height=3, aspect=1.5,legend=False, sharex=False, sharey=False)
plt.legend(loc='upper left')
plot.set_xticklabels(rotation=90)
plt.tight_layout()

#Create output
plot.savefig("output3.pdf")

Image taken from https://seaborn.pydata.org/tutorial/axis_grids.html

However since the plot may extend up to more than 300 plots, when I tried to export to pdf, the size of the chart is too big and big part of the plot get cropped out. I notice there are only 1 pages for this pdf output. Is there a way to create a multiple pages for this output?

EDIT:

As suggested by comments, I'm trying to use PdfPages

import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf")
for fig in range(1, plt.gcf().number + 1):
    plot= sns.catplot(data=df3, x="solutions", y="score", col="subject", col_wrap=3, hue="Value",height=3, aspect=1.5,legend=False, sharex=False, sharey=False)
    plt.legend(loc='upper left')
    plot.set_xticklabels(rotation=90)
    plt.tight_layout()
    
    pdf.savefig( fig )
pdf.close()

But it return error message:

<Figure size 432x288 with 0 Axes>

and return with pdf document with blank pages inside. Please help as I may not aware which part I did it wrongly

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you will have to split your plot in several figures so as to use the answer provided by @r-beginners

If you use catplot() you can use col_order= to specify which subject to show. You can loop through chunk of subjects using itertools.

Something like this:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    from itertools import zip_longest
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

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

N_plots_per_page = 9
for cols in grouper(data['subject'].unique(), N_plots_per_page):
    g = sns.catplot(data=data, x='solution', y='score', col='subject', col_wrap=3, kind='point', col_order=cols)
    pdf.savefig(g.fig)
pdf.close()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...