Learn Matplotlib for Data Science (Course III)July 9, 2020 2020-08-04 10:46
Learn Matplotlib for Data Science (Course III)
Saving 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 Matplotlib plot?
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.
In the next chapter, we will learn how to work with images in Matplotlib. Head over to the next and final chapter of the Matplotlib Full Course.