How to Save Seaborn Figure in Python
In this tutorial, we will discuss how to save a seaborn figure in an external file.
We will use the matplotlib.pyplot.savefig()
function, which can export it to an external file.
We need to specify the filename along with its format and the path of the file in the function itself.
For example,
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame(
{"Day 1": [7, 1, 5, 6, 3, 10, 5, 8], "Day 2": [1, 2, 8, 4, 3, 9, 5, 2]}
)
sns.lineplot(data=df)
plt.savefig("filename.png")
We can specify other file formats like jpeg
, png
, and more. We can also save the plot in non-image formats like PDF.
We can also customize the final figure using different arguments.
For example, we can specify the dpi
argument in the function. The dpi
means dots per inch so a higher value will result in a higher resolution of the final image.
For example,
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame(
{"Day 1": [7, 1, 5, 6, 3, 10, 5, 8], "Day 2": [1, 2, 8, 4, 3, 9, 5, 2]}
)
sns.lineplot(data=df)
plt.savefig("filename.png", dpi=300)
If we want, we can change the orientation using the orientation
parameter. The orientation is ‘portrait’ by default.
In the code below, we save the final figure in landscape orientation.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame(
{"Day 1": [7, 1, 5, 6, 3, 10, 5, 8], "Day 2": [1, 2, 8, 4, 3, 9, 5, 2]}
)
sns.lineplot(data=df)
plt.savefig("filename.png", orientation="horizontal")
Other arguments available are transparent
, frameon
, facecolor
, edgecolor
provide more customizations for the final exported figure.
Note that for recent versions of seaborn, directly using the savefig()
function might produce errors on some plots. For such cases, we should use the get_figure()
function also. This function gets the instance of the required figure, and we can then export it using the savefig()
function.
The following code demonstrates this.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.DataFrame(
{"Day 1": [7, 1, 5, 6, 3, 10, 5, 8], "Day 2": [1, 2, 8, 4, 3, 9, 5, 2]}
)
splot = sns.lineplot(data=df)
sfig = splot.get_figure()
sfig.savefig("filename.png", orientation="landscape")
Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.
LinkedIn