python - 将巨大的 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")
但是,由于该图可能会扩展到 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文档。请帮忙,因为我可能不知道我做错了哪一部分
解决方案
我认为您将不得不将您的情节分成几个数字,以便使用@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()
推荐阅读
- validation - Tcl 中的 %P 是什么?
- r - 使用迷你图将自定义格式化程序应用于格式化表中的多个列
- java - 为什么这个 javaagent 不能与 tomcat 一起工作
- typescript - 带有默认参数的打字稿类型推断
- ios - UIScrollView:如何在拖动操作触摸键盘之前启动键盘关闭交互操作(如 WhatsApp)?
- c# - 有必要使用 RequestDownloadAndInstallStorePackageUpdatesAsync() 来实际安装更新吗?
- python - 如何在不遇到“AmbiguousStep”异常的情况下拥有两个具有相同名称的步骤?
- sql - 在一个时间间隔内生成时间戳范围并查询所有重叠事件
- sql - 根据 Timestamp(Date) 填充查询结果中的行
- python - 如何在 freezegun 中使用忽略包?