如何从 matplotlib.figure.Figure 的列表中保存 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])

这有可能以另一种方式吗?

只需使用fig.savefig().这是为您的案例截取的代码:

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

最新更新