提问者:小点点

如何将sns.facetgrid保存到pdf格式


我有一个如下所示的数据帧:

import pandas as pd
foo = pd.DataFrame({'occasions': ['a', 'a', 'b', 'b'], 'val':[1,1,1,2]})

我试图用seaborn创建一个带有小面的直方图,我想把这个图像保存到pdf文件,所以我这样做:

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

pdf = PdfPages('exploration.pdf')
g = sns.FacetGrid(foo, col="occasions", margin_titles=True)
g.map(plt.hist,'val', color="steelblue")
g.set_titles(col_template = '{col_name}')
g.fig.suptitle('title')
plot_fig(g, pdf)

其中

def plot_fig(plot, pdf):
    try:
        fig = plot.draw()
    except:
        fig = plot
    pdf.savefig(fig, height=10, width=18, dpi=500, bbox_inches='tight', pad_inches=0.5)
    plt.close()

但是我得到了一个错误:valueerror:0x7F1CA2300780>处没有图形


共1个答案

匿名用户

我不知道您的pdfpages('exploration.pdf')文件是什么样子的,因此我无法确保它能正常工作,但一般来说,节省数字应该是这样工作的:

def plot_fig(plot, pdf):
    try:
        fig = plot.draw()
    except:
        fig = plot
    pdf.savefig(fig.fig, height=10, width=18, dpi=500, bbox_inches='tight', pad_inches=0.5)
    plt.close()

函数中称为fix的是seaborn.axisgrid.facetgrid。 要访问底层的matplotlib.figure并使用其savefig方法,需要使用fig.fig选择它。 也许将刻面网格重命名为fix以外的其他名称可能有助于减少混淆。