How to Save Figure in Matplotlib with Python 


               


How to Save Figure in Matplotlib with Python



Python


In this article, we show how to save a figure in matplotlib with Python.

So with matplotlib, the heart of it is to create a figure.

On this figure, you can populate it with all different types of data, including axes, a graph plot, a geometric shape, etc.

How can we save this figure after we create it?

And we can do this with the savefig() function.

With the savefig() function, we can save the figure to the current working directory.

We can save this figure as any name and any type of image file, such as png, jpg, etc.

This is shown in the following code below.



So the first thing we have to do is import matplotlib. We do this with the line, import matplotlib.pyplot as plt

We then create a variable fig, and set it equal to, plt.figure(). This creates an empty figure object.

We then add axes to the figure object.

We then have the x coordinates.

The Y coordinates are equal to the square of each of the x coordinates.

We then plot the x and y coordinates.

We then save the figure as 'Graph1.png'. The name of the file is 'Graph1' and the file format is png.

We then show the figure using the plt.show() function.

The png file will then be saved in the current working directory. You can find out the current working directory by importing os. And then calling the function, os.getcwd(). This is where the figure will be saved.

And this is how to save a figure in matplotlib with Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...