Matplotlib can save the plot to a file in PNG or JPG mage format. In this tutorial, we will learn how to get Matplotlib to save it’s output plot to such a file.
Why To Have Matplotlib Save Plot To File?
Matplotlib does a wonderful job in creating excellent plots and charts for us . However, the problem is it uses its own output window while displaying its results. While this is ok for us when learning things, it can’t be used in production. This is because in production we need these plots to be available in standard image formats. In other words, we want Matplotlib plot to be available as PNG or JPG file formats.
However, since this is such a basic requirement, Matplotlib already has a built-in function for this. So this function will enable us to use the Matplotlib plots even in production.
Understanding Matplotlib Savefig Function
The savefig function present in Matplotlib will help us in saving out output plot to an image file. This function has a very simple signature that looks like this:
savefig(fname, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None, metadata=None)
Woah that’s a mouthful you say? Well, the function signature might be looking daunting, but trust me, this is a very simple function to use. Let us go by the arguments passed to this function one by one:
fname - This is an argument with the path and filename to the output file dpi - This is the resolution of the output file in dots per inch quality - This argument will help us define the quality of the image we want. Lower quality will result in smaller size of the output file and vice versa. It varies between 1(worst) to 95(best) optimize - Bool variable. If set to true library will try to optimize the image
So in the above description, we have explained only the important parameters. But for the rest, you should check its official documentation. So in simple terms, the only parameters that we really want to use is the first parameter. It is the name and path of the output file. Rest of the other parameters are all optional.
So with this much knowledge, we can now start using this function. For easier understanding, let us just use the code and plot from our previous article. Currently, the code from our previous article looked like this:
import matplotlib.pyplot as plt x = range(1, 10) plt.plot(x, [xi*1 for xi in x]) plt.plot(x, [xi*2 for xi in x]) plt.plot(x, [xi*3 for xi in x]) plt.legend(['Blue=1x', 'Orange=2x', 'Green=3x']) plt.grid() plt.axis([0, 20, 0 , 40]) plt.xlabel('This is the X axis label') plt.ylabel('This is the Y axis label') plt.title('Dummy Plot') plt.show()
And it’s resulting output plot looked like this:
Up until now, we have been creating plots using Matplotlib that looked like above. However, so far we had not saved this plot to an image file. So In the next section we will learn how to instruct Matplotlib to save the plot to an image file.
Matplotlib Save Plot To File Example Code
As mentioned earlier, we can use Matplotlib to save the output plot to a file using its savefig() function. So in our code above, we simply need to call this function with appropriate arguments. However, to keep this example simple, we will not pass all the arguments. We will only pass the first argument that is the name and path of the resulting output file. But before that, we should also make one more little change to our current program.
Notice that in the current code, we use plt.show() to display the output plot. However, since we now want to save the plot instead of displaying it, we will remove this call. And in place of this, we will call our savefig() function.
So, the final code will look something like this:
import matplotlib.pyplot as plt x = range(1, 10) plt.plot(x, [xi*1 for xi in x]) plt.plot(x, [xi*2 for xi in x]) plt.plot(x, [xi*3 for xi in x]) plt.legend(['Blue=1x', 'Orange=2x', 'Green=3x']) plt.grid() plt.axis([0, 20, 0 , 40]) plt.xlabel('This is the X axis label') plt.ylabel('This is the Y axis label') plt.title('Dummy Plot') #plt.show() <------ Disable this line of code plt.savefig('Matplotlib_save_plot.png')
With that simple change of code, we can finally find the output plot saved into a file called Matplotlib_save_plot.png. Here is how the final output plot of Matplotlib saved in the file looks like:
So that is it for this tutorial. Hope it was easy enough for you to understand how to save output plot to a file. If you still have any more queries about it, do let us know in the comments below. Until next time, ciao! 🙂