簡體   English   中英

如何從matplotlib.figure.Figure的列表中保存matplotlib圖?

[英]How to save a matplotlib figure from a list of matplotlib.figure.Figure's?

創建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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM