Skill - Export a Matplotlib figure as an image or a pdf file
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- Introduction to Matplotlib plotting library
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")
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
- savefig documentation - https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.savefig
Comments
Post a Comment