Barplot savefig() 返回一个 AttributeError

Barplot savefig() returning an AttributeError

我正在将 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")

不用担心变量,它们已按预期填充,而且我在 iPyNB 中得到了一张漂亮的图表。 运行 然而,脚本中的代码产生 RuntimeError: Invalid DISPLAY variable.

在另一个线程之后,我修改了代码,将其放在脚本的顶部:

import matplotlib
matplotlib.use('Agg')

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

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

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

感谢任何帮助。

我猜你应该导入 pyplot。

import matplotlib.pyplot as plt
plt.savefig()

我通过更改

解决了这个问题
ax.savefig('file.png')

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

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

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

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