How to Save Seaborn Plot to a File (With Examples)


You can use the following syntax to save a Seaborn plot to a file:

import seaborn as sns
line_plot = sns.lineplot(x=x, y=y)
fig = line_plot.get_figure()
fig.savefig('my_lineplot.png')  

The following examples show how to use this syntax in practice.

Example 1: Save Seaborn Plot to PNG File

The following code shows how to save a Seaborn plot to a PNG file:

import seaborn as sns

#set theme style
sns.set_style('darkgrid')

#define data
x = [1, 2, 3, 4, 5, 6]
y = [8, 13, 14, 11, 16, 22]

#create line plot and save as PNG file
line_plot = sns.lineplot(x=x, y=y)
fig = line_plot.get_figure()
fig.savefig('my_lineplot.png')  

If we navigate to the location where we saved the file, we can view it:

Note that we could also use .jpg, .pdf, or other file extensions to save the plot to a different type of file.

Example 2: Save Seaborn Plot to PNG File with Tight Layout

By default, Seaborn adds padding around the outside of the figure.

To remove this padding, we can use the bbox_inches=’tight’ argument: 

fig.savefig('my_lineplot.png', bbox_inches='tight')  

Notice that there is minimal padding around the outside of the plot now.

Example 3: Save Seaborn Plot to PNG File with Custom Size

You can use the dpi argument to increase the size of the Seaborn plot when saving it to a file:

fig.savefig('my_lineplot.png', dpi=100)  

Notice that this plot is much larger than the previous two. The larger the value you use for dpi, the larger the plot will be.

Additional Resources

The following tutorials explain how to perform other common plotting functions in Seaborn:

How to Create Multiple Seaborn Plots in One Figure
How to Adjust the Figure Size of a Seaborn Plot
How to Add a Title to Seaborn Plots

Leave a Reply

Your email address will not be published.