【发布时间】:2020-07-09 07:37:44
【问题描述】:
我正在使用 matplotlib 和 seaborn 在一个 PDF 文件中创建我的绘图,该文件收集了所有打开的图形。
在简化的形式中,我的代码如下所示:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
# create random dataframe
df = pd.DataFrame(np.random.rand(30, 4), columns=['A', 'B', 'C', 'D'])
# create plots
ax1 = sns.lineplot(data=df.loc[:, ['A']], color='r')
ax2 = ax1.twinx()
ax2 = sns.lineplot(data=df.loc[:, ['B']], color='b', ax=ax2)
# this works in order to separate the plots into different figures
# but I do not want to call plt.figure() before every plot
#plt.figure()
ax3 = sns.scatterplot(data=df, x='C', y='D')
# create pdf file with plots
pp = PdfPages('plots.pdf')
figs = [plt.figure(n) for n in plt.get_fignums()]
for fig in figs:
fig.savefig(pp, format='pdf')
pp.close()
# close all existing figures
for fig in figs:
plt.close(fig)
但是这样一来,这些图形在 PDF 文件中被绘制成一页,因为它们属于同一个图形:
我可以使用 plt.figure() 为每个绘图手动创建一个新图形。
但是如何在创建 PDF 文件时自动在新图形中创建绘图,或者至少将所有绘图放在不同的图形上?
提前致谢!
【问题讨论】:
标签: python matplotlib seaborn