微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Seaborn FacetGrid 多页 pdf 绘图

如何解决Seaborn FacetGrid 多页 pdf 绘图

我正在尝试使用 FacetGrid 创建一个多页 pdf (https://seaborn.pydata.org/examples/many_facets.html)。有 20 个网格图像,我想将前 10 个网格保存在 pdf 的第一页,将后 10 个网格保存到 pdf 文件的第二页。我得到了从这个 (Export huge seaborn chart into pdf with multiple pages) 创建 mutipage 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[:,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,"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(...) 参数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。