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:
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
Trueto 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
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.
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:
- Introduction to Python (Free Course) - 1,000,000+ students already enrolled!
- Introduction to Data Science in Python- 400,000+ students already enrolled!
- Introduction to TensorFlow for Deep Learning with Python - 90,000+ students already enrolled!
- Data Science and Machine Learning Bootcamp with R - 70,000+ students already enrolled!