Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a plot in Seaborn with Python [duplicate]

I have a Pandas dataframe and try to save a plot in a png file. However, it seems that something doesn't work as it should. This is my code:

import pandas
import matplotlib.pyplot as plt
import seaborn as sns

sns.set(style='ticks')

df = pandas.read_csv("this_is_my_csv_file.csv")
plot = sns.distplot(df[['my_column_to_plot']])
plot.savefig("myfig.png")

And I have this error:

AttributeError: 'AxesSubplot' object has no attribute 'savefig'
like image 662
Tasos Avatar asked Jan 12 '16 09:01

Tasos


People also ask

How do you save a plot in Python Seaborn?

To save a plot in Seaborn, we can use the savefig() method.

Can we save a plot in Python?

Matplotlib plots can be saved as image files using the plt. savefig() function.

How do I save a figure as a PNG in Python?

To save plot figure as JPG or PNG file, call savefig() function on matplotlib. pyplot object. Pass the file name along with extension, as string argument, to savefig() function.


1 Answers

You could save any seaborn figure like this.

Suppose If you want to create a violin plot to show the salary distribution gender wise. You could do it like this and will save it using the get_figure method.

ax = sns.violinplot(x="Gender", y="Salary", hue="Degree", data=job_data)
#Returns the :class:~matplotlib.figure.Figure instance the artist belongs to
fig = ax.get_figure()
fig.savefig('gender_salary.png')
like image 83
Aman Tandon Avatar answered Oct 22 '22 13:10

Aman Tandon