Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing which figures to show on-screen and which to save to a file using Python's matplotlib

I'd like to create different figures in Python using matplotlib.pyplot. I'd then like to save some of them to a file, while others should be shown on-screen using the show() command.

However, show() displays all created figures. I can avoid this by calling close() after creating the plots which I don't want to show on-screen, like in the following code:

import matplotlib.pyplot as plt

y1 = [4, 2, 7, 3]
y2 = [-7, 0, -1, -3]

plt.figure()
plt.plot(y1)
plt.savefig('figure1.png')
plt.close()

plt.figure()
plt.plot(y2)

plt.show()
plt.close('all')

This saves the first figure and shows the second one. However, I get an error message:

can't invoke "event" command: application has been destroyed while executing

Is it possible to select in a more elegant way which figures to show?

Also, is the first figure() command superfluous? It doesn't seem to make a different whether I give it or not.

Many thanks in advance.

like image 561
gandi2223 Avatar asked May 23 '11 06:05

gandi2223


People also ask

How do I save a figure to a file in python?

Saving a plot on your disk as an image file Now if you want to save matplotlib figures as image files programmatically, then all you need is matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.

How do I save multiple figures in python?

MatPlotLib with Python Create a new figure (fig2) or activate an existing figure using figure() method. Plot the Second line using plot() method. Initialize a variable, filename, to make a pdf file. Create a user-defind function, save_multi_image, and call it to save all the open matplotlib figures in one file at once.

How do I save a figure without displaying it in python?

Simply call plt. close() at the end of each plot instead of plt. show() and they won't be displayed.


1 Answers

The better way is to use plt.clf() instead of plt.close(). Moreover plt.figure() creates a new graph while you can just clear previous one with plt.clf():

import matplotlib.pyplot as plt

y1 = [4, 2, 7, 3]
y2 = [-7, 0, -1, -3]

plt.figure()
plt.plot(y1)
plt.savefig('figure1.png')
plt.clf()

plt.plot(y2)

plt.show()
plt.clf()

This code will not generate errors or warnings such can't invoke "event" command...

like image 72
George Avatar answered Oct 07 '22 09:10

George