Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I was trying to write a quick-and-dirty script to generate plots easily. For that, I was using the following code (I took it from the Matplotlib documentation):

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

But 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?

2 Answers

0 votes
by (106k points)

When you are using Save plot you can use specify .savefig() as an extension to the file:-

from matplotlib import pyplot as plt

plt.savefig('foo.png') 

plt.savefig('foo.pdf')

The use of  .savefig() Will give a rasterized or vectorized output respectively, both which could be useful.

0 votes
by (108k points)

You can also refer to the below link as with the help of the below code, you can able to reopen the image whenever you want:

import matplotlib.pyplot as plt

fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis

ax.plot([0,1,2], [10,20,3])

fig.savefig('path/to/save/image/to.png')   # save the figure to file

plt.close(fig)    # close the figure window

For more information regarding the same, do refer to the Python certification course. 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jan 5, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 9, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers

500 comments

108k users

Browse Categories

...