如何将多个 Seaborn 图保存到单个 pdf 文件中
问题描述:
所以我试图将我在 for 循环中创建的多个图保存到一个 pdf 文件中.我已经在 SO 上搜索并拼凑了一些似乎有效的代码,只是它不保存它创建的 pdf 的数字但没有任何内容.
So I'm trying to save multiple plots that i create in a for loop into a single pdf file. I've searched around on SO and pieced together some code that seems to work except it doesn't save the figures it creates a pdf but without anything in it.
这是重现它的代码:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
dftest = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 5)),
columns=['a', 'b', 'c', 'd', 'e'])
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages('count.pdf') as pdf_pages:
df1 = dftest.select_dtypes([np.int, np.float, np.object])
for i, col in enumerate(df1.columns):
plt.figure(i)
countplot = sns.countplot(x=col, data=df1)
pdf_pages.savefig(countplot.fig)
答
保存 plt.figure 对我有用
Saving the plt.figure works for me
with PdfPages('count.pdf') as pdf_pages:
df1 = dftest.select_dtypes([np.int, np.float, np.object])
for i, col in enumerate(df1.columns):
figu = plt.figure(i)
countplot = sns.countplot(x=col, data=df1)
pdf_pages.savefig(figu)