Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving plot from seaborn

When I try to save my plot working with seaborn, like this:

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
from pylab import savefig

array = [[100,0], 
        [33,67]]

df_cm = pd.DataFrame(array)

svm = sn.heatmap(df_cm, annot=True,cmap='coolwarm', linecolor='white', linewidths=1)

svm.savefig('svm_conf.png', dpi=400)

I get this error

AttributeError                            Traceback (most recent call last)
<ipython-input-71-5c0ae9cda020> in <module>()
----> 1 svm.savefig('svm_conf.png', dpi=400)

AttributeError: 'AxesSubplot' object has no attribute 'savefig'

I have saved some boxplots before, with the same code, but this time, it doesn't work.

like image 214
rnv86 Avatar asked Aug 08 '17 13:08

rnv86


People also ask

How do I save a plot in Python?

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

How do I save a plot as a JPEG 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

Actually what you would need to do is:

  • Retrieve the figure from the object returned by sn.heatmap
  • Then and only then save the figure

See the last 2 lines below:

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
from pylab import savefig

array = [[100,0], 
        [33,67]]

df_cm = pd.DataFrame(array)

svm = sn.heatmap(df_cm, annot=True,cmap='coolwarm', linecolor='white', linewidths=1)

figure = svm.get_figure()    
figure.savefig('svm_conf.png', dpi=400)
like image 60
Adonis Avatar answered Sep 20 '22 12:09

Adonis