Thanks to theidioms.com

Saving Plots in Matplotlib

matplotlib full course
Tutorial

Saving Plots in Matplotlib

Greetings! Some links on this site are affiliate links. That means that, if you choose to make a purchase, The Click Reader may earn a small commission at no extra cost to you. We greatly appreciate your support!

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.


Saving Plots in MatplotlibSaving Plots in Matplotlib

Do you want to learn Python, Data Science, and Machine Learning while getting certified? Here are some best selling Datacamp courses that we recommend you enroll in:

  1. Introduction to Python (Free Course) - 1,000,000+ students already enrolled!
  2. Introduction to Data Science  in Python- 400,000+ students already enrolled!
  3. Introduction to TensorFlow for Deep Learning with Python - 90,000+ students already enrolled!
  4. Data Science and Machine Learning Bootcamp with R - 70,000+ students already enrolled!

Leave your thought here

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