python - Seaborn FacetGrid 多页 pdf 绘图
问题描述
我正在尝试使用 FacetGrid 从这里创建一个多页 pdf(https://seaborn.pydata.org/examples/many_facets.html)。有 20 个网格图像,我想将前 10 个网格保存在 pdf 的第一页,将后 10 个网格保存到 pdf 文件的第二页。我得到了创建多页 pdf 文件的想法(将巨大的 seaborn 图表导出为多页的 pdf)。此示例适用于 sns.catplot() 但在我的情况下 (sns.FacetGrid) 输出 pdf 文件有两页,每页都有 20 个网格,而不是在每页中划分 10 个网格。
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Create a dataset with many short random walks
rs = np.random.RandomState(4)
pos = rs.randint(-1, 2, (20, 5)).cumsum(axis=1)
pos -= pos[:, 0, np.newaxis]
step = np.tile(range(5), 20)
walk = np.repeat(range(20), 5)
df = pd.DataFrame(np.c_[pos.flat, step, walk],
columns=["position", "step", "walk"])
# plotting FacetGrid
def grouper(iterable, n, fillvalue=None):
from itertools import zip_longest
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages("output.pdf") as pdf:
N_plots_per_page = 10
for cols in grouper(df["walk"].unique(), N_plots_per_page):
# Initialize a grid of plots with an Axes for each walk
grid = sns.FacetGrid(df, col="walk", hue="walk", palette="tab20c",
col_wrap=2, height=1.5)
# Draw a horizontal line to show the starting point
grid.map(plt.axhline, y=0, ls=":", c=".5")
# Draw a line plot to show the trajectory of each random walk
grid.map(plt.plot, "step", "position", marker="o")
# Adjust the tick positions and labels
grid.set(xticks=np.arange(5), yticks=[-3, 3],
xlim=(-.5, 4.5), ylim=(-3.5, 3.5))
# Adjust the arrangement of the plots
grid.fig.tight_layout(w_pad=1)
pdf.savefig()
解决方案
您缺少调用的col_order=cols
参数grid = sns.FacetGrid(...)
。
推荐阅读
- reactjs - 我正在尝试制作反应贝宝按钮,以更改道具更改的计费金额
- sql - SQL Server 代理无法运行 SQLCMD
- playframework - WSO2IS-Axis2 连接未正确关闭。它保持在 CLOSE_WAIT 状态,直到达到最大打开文件限制
- python-3.x - 如何在python中读取算术运算符作为输入
- android - 如何修复Android UI闪烁的错误?
- reactjs - 如何在窗口的上下文中接收来自 Firebase 的通知(以及服务工作者)
- sql - SQL查询中为什么会引用未知列
- xml - 如果 xml 文件中的字符串匹配,则获取文件名
- gatsby - Gatsby,“gatsby--image”在项目“构建”时不显示图像,但在开发时正确显示
- sass - 在 SASS 中给定 x 个具有固定直径的圆的圆周围定位圆