CiaranWelsh
CiaranWelsh

Reputation: 7689

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

Is it possible to save a matplotlib figure after it has been created? For instance:

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)

produces the figures in a list:

[<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>]

I would like to not have to explicitly save the plot directly after creation but have the option to do it later (maybe from within another class). The ideal would be to pass the fig to plt.savefig, but there doesn't seem to be a slot available for this type of usage.

To clarify. I would like to do:

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

Is this possible in another way?

Upvotes: 2

Views: 1777

Answers (1)

Ferran Par&#233;s
Ferran Par&#233;s

Reputation: 636

Just use fig.savefig(). Here is a code snipped for your case:

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

Upvotes: 4

Related Questions