32

I'm converting an iPython notebook to a python script, just trying to output the results of a couple Seaborn plots as png files. Code:

import seaborn as sns

...

sns.set_style("whitegrid")
ax = sns.barplot(x=range(1,11), y=[ (x/nrows)*100 for x in addr_pop ], palette="Blues_d")
ax.savefig("html/addr_depth.png")

Don't worry about the variables, they're populated as expected, and I get a great-looking chart in iPyNB. Running the code within a script, however, yields RuntimeError: Invalid DISPLAY variable.

Following another thread, I modified the code, putting this at the top of the script:

import matplotlib
matplotlib.use('Agg')

And tried again. This time, it doesn't seem like the savefig() method is available for the plot at all:

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

All the results searching out this error are related to pandas and a plot that is already being displayed. I'm just trying to get Seaborn to output the fig to a file, ideally without displaying it at all.

Any help is appreciated.

economy
  • 4,035
  • 6
  • 29
  • 37

2 Answers2

116

I solved the issue by changing

ax.savefig('file.png')

to

ax.figure.savefig('file.png')

I guess accessing the figure directly is one way to get to the savefig() method for the barplot.

@WoodChopper also has a working solution, but it requires another import statement, and utilizing pyplot's savefig() directly.

Either solution does require setting matplotlib.use('Agg') to get around the DISPLAY variable error. As the referenced post noted, this has to be set before importing other matplotlib libraries.

Community
  • 1
  • 1
economy
  • 4,035
  • 6
  • 29
  • 37
13

I guess you should import pyplot.

import matplotlib.pyplot as plt
plt.savefig()
WoodChopper
  • 4,265
  • 6
  • 31
  • 55
  • 1
    OK, that does work. I'm a little confused as to why, but this does solve the issue. I also found a way to do it without the need to import pyplot separately. Changing `ax.savefig()` to `ax.figure.savefig()` has the same effect, and seems a little cleaner. Maybe someone can comment and shed some light on the differences. – economy Nov 09 '15 at 19:40
  • 2
    You could read up on the object-oriented interface, for example [this tutorial](http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut2.html) is very clear. It should help you see how these things all fit together. – mwaskom Nov 09 '15 at 22:07
  • 2
    Didn't work for me, I have to use `.figure.` – FiReTiTi Jun 24 '21 at 21:58