将巨大的 seaborn 图表导出为多页的 pdf [英] Export huge seaborn chart into pdf with multiple pages
问题描述
我创建了一个使用 seaborn catplot 生成大量图表的程序.这是我的代码示例,其中说明了最终图表的外观.
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")
然而,由于绘图可能会扩展到 300 多个绘图,当我尝试导出为 pdf 时,图表的大小太大,并且大部分绘图被裁剪掉了.我注意到这个 pdf 输出只有 1 页.有没有办法为此输出创建多个页面?
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?
正如评论所建议的,我正在尝试使用 PdfPages
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()
但它返回错误信息:
<Figure size 432x288 with 0 Axes>
并返回带有空白页的pdf文档.请帮助,因为我可能不知道我做错了哪一部分
and return with pdf document with blank pages inside. Please help as I may not aware which part I did it wrongly
推荐答案
我认为你必须把你的情节分成几个数字才能使用 @r-beginners 提供的答案
I think you will have to split your plot in several figures so as to use the answer provided by @r-beginners
如果您使用 catplot()
,您可以使用 col_order=
指定要显示的主题.您可以使用 itertools<遍历 subjects
块/a>.
If you use catplot()
you can use col_order=
to specify which subject to show. You can loop through chunk of subjects
using itertools.
像这样:
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()
这篇关于将巨大的 seaborn 图表导出为多页的 pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!