Python Barplot savefig() 返回一个 AttributeError

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33616557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:37:33  来源:igfitidea点击:

Barplot savefig() returning an AttributeError

pythonmatplotlibseaborn

提问by economy

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:

我正在将 iPython 笔记本转换为 python 脚本,只是尝试将几个 Seaborn 图的结果输出为 png 文件。代码:

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.

不要担心变量,它们按预期填充,我在 iPyNB 中得到了一个漂亮的图表。但是,在脚本中运行代码会产生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:

并再次尝试。这一次,该savefig()方法似乎根本不适用于该图:

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.

搜索到此错误的所有结果都与 Pandas 和已经显示的图有关。我只是想让 Seaborn 将无花果输出到一个文件中,理想情况下根本不显示它。

Any help is appreciated.

任何帮助表示赞赏。

采纳答案by economy

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.

我想直接访问图形是获取savefig()条形图方法的一种方法。

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

@WoodChopper 也有一个可行的解决方案,但它需要另一个导入语句,并savefig()直接使用 pyplot 。

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

这两种解决方案都需要设置matplotlib.use('Agg')来解决 DISPLAY 变量错误。正如引用的帖子所指出的,必须在导入其他 matplotlib 库之前进行设置。

回答by WoodChopper

I guess you should import pyplot.

我想你应该导入 pyplot。

import matplotlib.pyplot as plt
plt.savefig()