Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save plot to image file instead of displaying it using Matplotlib

I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from Matplotlib documentation) as a starting point:

from pylab import figure, axes, pie, title, show  # Make a square figure and axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0.1, 0.8, 0.8])  labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' fracs = [15, 30, 45, 10]  explode = (0, 0.05, 0, 0) pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True) title('Raining Hogs and Dogs', bbox={'facecolor': '0.8', 'pad': 5})  show()  # Actually, don't show, just save to foo.png 

I don't want to display the plot on a GUI, instead, I want to save the plot to a file (say foo.png), so that, for example, it can be used in batch scripts. How do I do that?

like image 829
Homunculus Reticulli Avatar asked Mar 08 '12 17:03

Homunculus Reticulli


People also ask

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

We can simply save plots generated from Matplotlib using savefig() and imsave() methods. If we are in interactive mode, the plot might get displayed. To avoid the display of plot we use close() and ioff() methods.

How do I save a plot as an image in Python?

Matplotlib plots can be saved as image files using the plt. savefig() function.

How will you save a plot as a PNG image in matplotlib?

To save plot figure as JPG or PNG file, call savefig() function on matplotlib. pyplot object. Pass the file name along with extension, as string argument, to savefig() function.

Which function can be used to export generated graph in matplotlib to PNG?

Syntax of savefig() function fname : path or name of output file with extension. If extension is not provided plot is saved as png file.


1 Answers

While the question has been answered, I'd like to add some useful tips when using matplotlib.pyplot.savefig. The file format can be specified by the extension:

from matplotlib import pyplot as plt  plt.savefig('foo.png') plt.savefig('foo.pdf') 

Will give a rasterized or vectorized output respectively, both which could be useful. In addition, there's often an undesirable, whitespace around the image, which can be removed with:

plt.savefig('foo.png', bbox_inches='tight') 

Note that if showing the plot, plt.show() should follow plt.savefig(), otherwise the file image will be blank.

like image 62
Hooked Avatar answered Oct 03 '22 04:10

Hooked