为 matplotlib 图自动创建新图形

Posted

技术标签:

【中文标题】为 matplotlib 图自动创建新图形【英文标题】:Create new figure automatically for matplotlib plots 【发布时间】: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 文件时自动在新图形中创建绘图,或者至少将所有绘图放在不同的图形上?

提前致谢!

【问题讨论】:

【参考方案1】:

您在这里将所有数字保存到同一个 pdf 中:

pp = PdfPages('plots.pdf')
[...]
for fig in figs:
    fig.savefig(pp, format='pdf')

尝试动态更改 pdf 的名称,这样每个图形都会有一个新文件

【讨论】:

实际上,我希望它们都在一个 pdf 文档中。

以上是关于为 matplotlib 图自动创建新图形的主要内容,如果未能解决你的问题,请参考以下文章

如何告诉 Matplotlib 创建第二个(新)图,然后在旧图上绘制?

在不手动计算子图数量的情况下创建 matplotlib 子图?

ios分数打开图

matplotlib:创建新图形并保存到文件

Python机器学习(六十六)Matplotlib 基本概念

使用 Matplotlib 创建 CSV 数据的实时图