Matplotlib save figure to image file
Save figure Matplotlib can save plots directly to a file using savefig(). The method can be used like this:
fig.savefig('plot.png')
Complete example:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
#plt.show()
fig.savefig('plot.png')
To change the format, simply change the extension like so:
fig.savefig('plot.pdf')
You can open your file using
display plot.png
or open it in an image or pdf viewer,
A plot saved to a pdfPrevent cropped labels and borders
Sometimes saved plot files cut off axis labels or legends around the edge. To fix this, pass bbox_inches='tight':
fig.savefig('plot.png', bbox_inches='tight')
Save high resolution images
By default Matplotlib saves images at 100 DPI. For publications, reports, or high-DPI screens, increase the resolution with the dpi parameter:
fig.savefig('plot_high_res.png', dpi=300, bbox_inches='tight')

Save with transparent background
To save an image without a white background so it fits into dark websites or slide presentations, set transparent=True:
fig.savefig('plot_transparent.png', transparent=True)