How to save a plot using Matplotlib

1 min

You will end needing to save your plots.

Matplotlib comes with a simple method to save your plots in images formats so that you can share it or add it to your research/analysis.

To do that, we use the plt.savefig() method

# We import the libraries
import matplotlib.pyplot as plt
import pandas as pd

# We read a sample dataset from the web.
df = pd.read_csv('https://raw.githubusercontent.com/'\
                 'mwaskom/seaborn-data/master/iris.csv')

# We set up our canvas
fig, axes = plt.subplots(1,
                         1,
                         figsize=(6,4))

# We do a boxplot plot on the axes
axes.boxplot(df["sepal_length"])

# We set a title
axes.set_title("Sepal Length Boxplot")

# Fixing the layout to fit the size
fig.tight_layout()

# We save the figure
plt.savefig("simple_boxplot.png")
Saving the plot as an image format

Here you are ! You now know how to save plots.

More on plots

If you want to know more about how to add labels, plot different types of plots, etc... checkout the other articles I wrote on the topic, just here :

Matplotlib - The Python You Need
We gathered the only Python essentials that you will probably ever need.