Matplotlib save figure to image file

Related course
The course below is all about data visualization:

Save figure
Matplotlib can save plots directly to a file using savefig().
The method can be used like this:


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')

To change the format, simply change the extension like so:


You can open your file using

display plot.png

or open it in an image or pdf viewer,


A plot saved to a pdf


Matplotlib legend
Matplotlib update plot
This entry was posted in Plotting and tagged , . Bookmark the permalink.