如何从matplotlib.figure.Figure的列表中保存matplotlib图?

时间:2018-05-02 15:27:03

标签: python matplotlib

创建后可以保存matplotlib数字吗?例如:

import matplotlib.pyplot as plt
import numpy
normal = numpy.random.normal(0, 1, 100)
df = pandas.DataFrame(normal.reshape((10, 10)))

figs = []

for i in df.keys():
    fig = plt.figure()
    plt.plot(df.index, df[i])
    figs.append(fig)

print(figs)

在列表中生成数字:

[<matplotlib.figure.Figure object at 0x7f8f158f1b00>, <matplotlib.figure.Figure object at 0x7f8f100d6128>, <matplotlib.figure.Figure object at 0x7f8f10081da0>, <matplotlib.figure.Figure object at 0x7f8f0a0354a8>, <matplotlib.figure.Figure object at 0x7f8f09fbd470>, <matplotlib.figure.Figure object at 0x7f8f09f18b00>, <matplotlib.figure.Figure object at 0x7f8f09f12d68>, <matplotlib.figure.Figure object at 0x7f8f09e88860>, <matplotlib.figure.Figure object at 0x7f8f09ebbc18>, <matplotlib.figure.Figure object at 0x7f8f09d6e198>]

我希望不必在创建后直接显式保存绘图,但可以选择稍后执行(可能来自另一个类)。理想情况是将fig传递给plt.savefig,但似乎没有可用于此类用法的插槽。

澄清。我想这样做:

fname = r'/path/to/file.jpg'
plt.savefig(fname, fig=figs[2])

这可能以另一种方式吗?

1 个答案:

答案 0 :(得分:2)

只需使用fig.savefig()即可。这是针对您的案例剪切的代码:

for idx, fig in enumerate(figs):
    fname = '{}_tmp.jpg'.format(idx)
    fig.savefig(fname)