Apart from showing the plot, Matplotlib also enables you to save the plot as a PNG, JPG, and SVG.
To save the plot as an image file, you must call the savefig()
function and pass the filename with the .png or .jpg extension.
import matplotlib.pyplot as plt #Code for plotting the graph plt.savefig('output.png') #save the plot as PNG file plt.savefig('output.jpg') #save the plot as JPG file plt.savefig('output.svg') #save the plot as SVG file
Note: If you are running plt.show()
and plt.savefig()
functions then make sure plt.savefig()
comes before plt.show()
.
In this code, we will draw a line chart and save it as "sales.jpg".
import matplotlib.pyplot as plt x = [2004, 2005, 2006, 2007] y = [1102, 2274, 900, 1482] plt.plot(x, y, color='red') plt.title('Yearly Sales Data') plt.xlabel('Years') plt.ylabel('Sales') plt.savefig('sales.jpg')
Output