Thanks to

Saving Plots in Matplotlib

matplotlib full course

Saving Plots in Matplotlib

Saving Plots in MatplotlibSaving Plots in Matplotlib

In the previous chapters, we have learned about how to plot 2D and 3D plots in Matplotlib. In this chapter, we will get familiar with saving plots in Matplotlib.

How to save a plot in Matplotlib?

A Matplotlib Plot can be saved by providing the image path and the plot to the savefig() function of Matplotlib pyplot.

# Libraries/Modules import conventions
import matplotlib.pyplot as plt  

# For interactive matplotlib sessions, turn on the matplotlib inline mode
%matplotlib inline

# Dummy Data
X = [1, 2, 3, 4]
Y = [2, 4, 6, 8]

# plot() is used for plotting a line plot
plt.plot(X, Y)

# Adding title, xlabel and ylabel
plt.title('A Basic Line Plot') #Title of the plot
plt.xlabel('X-axis') #X-Label
plt.ylabel('Y-axis') #Y-Label

# Saving the plot
plt.savefig('figureName.png') # You can also specify full path to storage

You can find the saved plot in the folder from where you ran the Python script/Jupyter Notebook cell. The image will look like this:

saving plots in matplotlib

Some other options for savefig()

The following are some few other options that can be passed on to the savefig() function of matplotlib pyplot to further customize the image to be saved:

  • dpi: Set the resolution of the file to a numeric value.
  • transparent: Can be set to True to make the background of the plot transparent.
  • bbox_inches: To alter the size of the bounding box (whitespace) around the output image. In most cases, if no bounding box is desired, using bbox_inches='tight' is ideal.

Now we know about saving plots in Matplotlib.

Head over to the next and final chapter of this course on ‘Working with Images in Matplotlib‘ where we will learn how to work with images in Matplotlib.

Are you interested in working with data? Get a free trial month of LinkedIn Learning and learn Data Science and Machine Learning courses using Python, R, and SQL from top instructors.

Enroll in any one of the courses from the following fields today on LinkedIn Learning and start your free month of learning:

Disclaimer: When you subscribe to LinkedIn Learning, we may earn a small commission as an affiliate. We love the platform so much so that we have been using it ourselves at The Click Reader.

Saving Plots in MatplotlibSaving Plots in Matplotlib

Leave your thought here

Your email address will not be published. Required fields are marked *