Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将sns.facetgrid保存为pdf_Python_Python 3.x_Matplotlib_Seaborn - Fatal编程技术网

Python 如何将sns.facetgrid保存为pdf

Python 如何将sns.facetgrid保存为pdf,python,python-3.x,matplotlib,seaborn,Python,Python 3.x,Matplotlib,Seaborn,我有一个如下所示的数据帧: import pandas as pd foo = pd.DataFrame({'occasions': ['a', 'a', 'b', 'b'], 'val':[1,1,1,2]}) def plot_fig(plot, pdf): try: fig = plot.draw() except: fig = plot pdf.savefig(fig.fig, height=10, width=18, dpi=5

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

import pandas as pd
foo = pd.DataFrame({'occasions': ['a', 'a', 'b', 'b'], 'val':[1,1,1,2]})
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()
我正在尝试使用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)
在哪里


但是我得到了一个错误:
ValueError:No figure
,你知道我为什么以及如何修复它吗?

我不知道你的
PdfPages('exploration.pdf')
文件是什么样子的,因此我不能确定这是否有效,但一般来说,保存数字应该是这样的:

import pandas as pd
foo = pd.DataFrame({'occasions': ['a', 'a', 'b', 'b'], 'val':[1,1,1,2]})
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()
函数中称为
fig
的是
seaborn.axisgrid.FaceGrid
。要访问基础
matplotlib.figure
并使用其
savefig
方法,需要使用
fig.fig
选择它。也许将刻面网格重命名为
fig
之外的其他内容可能有助于减少混淆