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
之外的其他内容可能有助于减少混淆