15.1 C
London
Friday, July 5, 2024
HomeSoftware TutorialsPythonHow to Save Seaborn Plot to a File (With Examples)

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

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories