我尝试了以下代码(test_seborn .py):

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
import seaborn as sns
sns.set()
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
fig = sns_plot.get_figure()
fig.savefig("output.png")
#sns.plt.show()

但是我得到了这个错误:

  Traceback (most recent call last):
  File "test_searborn.py", line 11, in <module>
    fig = sns_plot.get_figure()
AttributeError: 'PairGrid' object has no attribute 'get_figure'

我希望最终的output.png会存在,看起来像这样:

我该如何解决这个问题?


当前回答

仅供参考,以下命令在seaborn 0.8.1中工作,所以我猜最初的答案仍然有效。

sns_plot = sns.pairplot(data, hue='species', size=3)
sns_plot.savefig("output.png")

其他回答

我不能得到其他答案的工作,最后得到这个工作为我matplotlib==3.2.1。如果你是在for循环或一些迭代方法中这样做,尤其如此。

sns.scatterplot(
    data=df_hourly, x="date_week", y="value",hue='variable'
)
plt.savefig('./f1.png')
plt.show()

注意,savefig必须在show调用之前。否则将保存一个空映像。

在seaborn 0.8.1中使用sn .figure.savefig("output.png")会得到一个错误。

而不是使用:

import seaborn as sns

df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")

也可以只创建一个matplotlib图形对象,然后使用plt.savefig(…):

from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

df = sns.load_dataset('iris')
plt.figure() # Push new figure on stack
sns_plot = sns.pairplot(df, hue='species', size=2.5)
plt.savefig('output.png') # Save that figure

我使用distplot和get_figure成功保存图片。

sns_hist = sns.distplot(df_train['SalePrice'])
fig = sns_hist.get_figure()
fig.savefig('hist.png')

上面的一些解决方案对我不起作用。当我尝试时,没有找到.fig属性,我无法直接使用.savefig()。然而,真正起作用的是:

sns_plot.figure.savefig("output.png")

我是一个新的Python用户,所以我不知道这是否是由于更新。我想提一下,以防其他人遇到和我一样的问题。