首页 > 解决方案 > 将巨大的 seaborn 图表导出为多页的 pdf

问题描述

我创建了一个使用 seaborn catplot 生成大量图表的程序。这是我的代码示例,说明了最终图表的外观。

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")

图片取自 https://seaborn.pydata.org/tutorial/axis_grids.html

但是,由于该图可能会扩展到 300 多个图,因此当我尝试导出为 pdf 时,图表的大小太大,并且图的大部分都被裁剪掉了。我注意到这个 pdf 输出只有 1 页。有没有办法为此输出创建多个页面?

编辑:

正如评论所建议的,我正在尝试使用 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文档。请帮忙,因为我可能不知道我做错了哪一部分

标签: pythonmatplotlibseaborn

解决方案


我认为您将不得不将您的情节分成几个数字,以便使用@r-beginners 提供的答案

如果您使用catplot(),您可以使用col_order=来指定要显示的主题。您可以循环subjects使用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()

推荐阅读