16

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'
Tasos
  • 7,325
  • 18
  • 83
  • 176

3 Answers3

23

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')
Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93
Aman Tandon
  • 1,379
  • 2
  • 13
  • 26
15

You could use plt.savefig because your picture will come up when you'll call plt.show()

Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93
  • 1
    @Tasos it can be that they made a Figure object, with `fig = plt.Figure()`. Then you can save the figure with `fig.savefig()` – Mathias711 Jan 12 '16 at 09:48
2

Use plt.savefig('yourTitle.png')

If you want to pass a variable:

plt.savefig("yourTitleDataSet{0}.png".format(dataset))
matsjoyce
  • 5,744
  • 6
  • 31
  • 38
galucero
  • 353
  • 1
  • 4
  • 9