Export a Matplotlib figure as an image or a pdf file

matplotlib_export_figure

Skill - Export a Matplotlib figure as an image or a pdf file

Table of Contents

Skills Required

Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision


Matplotlib is a plotting library in the scipy ecosystem of libraries.

In this post we will try to understand how to export a matplotlib figure as an image or pdf file

Please make sure that you covered the post on basics


Using “savefig” method to save the figure as a file

import matplotlib.pyplot as plt

# create a plotting area and get the figure, axes handle in return
fig, ax = plt.subplots()

# plot some data
ax.plot([0,4,8,12], [6,8,4,2])
ax.plot([0,3,9,12,15,18], [2,1,9,6,4,3])

# save figure as a png file
fig.savefig("output.png")
fig.savefig(r"C:\figure.jpg")
fig.savefig(r"C:\testFile.pdf")

basic multiple plots output
As shown in the above code, just by using the savefig method on a matplotlib figure, we can export the figure as a pdf or image file.

Note that we can also provide an absolute file path like C:\testFile.pdf so that the file can be stored in any desired location of the computer

Video

You can the video on this post here


References


Table of Contents

Comments