【问题标题】:How to save a Seaborn plot into a file如何将 Seaborn 图保存到文件中
【发布时间】:2015-11-21 13:30:48
【问题描述】:

我尝试了以下代码(test_seaborn.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 会存在并且看起来像这样:

我该如何解决这个问题?

【问题讨论】:

  • @Terry Wang's answer down below 为我工作 - Python 2.7.12seaborn 0.7.1
  • seaborn 0.9 的单行:sns.regplot(x='age', y='income', data=pd.read_csv('income_data.csv')).get_figure().savefig('income_f_age.png')

标签: python pandas matplotlib seaborn


【解决方案1】:

以下调用允许您访问该图(Seaborn 0.8.1 兼容):

swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig("out.png") 

如之前在this answer 中看到的那样。

建议的解决方案与 Seaborn 0.8.1 不兼容。他们给出了以下错误,因为 Seaborn 界面已更改:

AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure

AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function

更新: 我最近使用了来自 seaborn 的 PairGrid 对象来生成类似于 this example 中的图。 在这种情况下,因为GridPlot 不是像sns.swarmplot 这样的绘图对象,所以它没有get_figure() 函数。 可以通过以下方式直接访问 matplotlib 图:

fig = myGridPlotObject.fig

【讨论】:

  • 我最近使用了 seaborn 中的 PairGrid 对象,如示例所示
  • 这是唯一适用于 PairGrid 和 JointGrid 的答案,我认为它应该被接受。
  • get_figure 保存图的要求很烦人。应该可以使用在线将绘图保存到文件中。
【解决方案2】:

我无法得到其他答案,最终得到了这个为我工作的 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 调用之前。否则将保存一个空图像。

【讨论】:

    【解决方案3】:

    2019 年搜索者的行数减少:

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    df = sns.load_dataset('iris')
    sns_plot = sns.pairplot(df, hue='species', height=2.5)
    plt.savefig('output.png')
    

    更新说明:size 已更改为 height

    【讨论】:

    • 它产生白色图像!
    • @user_007 不确定您为什么会得到白色图像。我今天刚刚测试了代码,对 Jupyter Notebook 和输出文件都很好。您可能想要更新您的控制台/Python 并检查您的计算机查看设置。
    【解决方案4】:

    也可以只创建一个matplotlib figure 对象,然后使用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
    

    【讨论】:

    • 至少不适用于displot
    【解决方案5】:

    这对我有用

    import seaborn as sns
    import matplotlib.pyplot as plt
    %matplotlib inline
    
    sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
    plt.savefig('holiday-vs-count.png')
    

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

      • 虽然该代码可以运行,但它并不完整。标题说“如何将 Seaborn 绘图保存到文件中”,这更笼统。不幸的是,提议的解决方案适用于pairplot,但它引发了其他“种类”图的例外。希望在未来的版本中,会有一种更统一的方式从 seaborn 图中获取“figure”对象。
      【解决方案7】:

      在 seaborn 0.8.1 中使用 sns.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")
      

      【讨论】:

        【解决方案8】:

        我使用distplotget_figure保存图片成功。

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

        【讨论】:

        • 适用于我的环境:python 3.5.6seaborn 0.9.0 中的函数 sns.distplot() 。另外,函数sns.pairplot()不需要get_figure()这一行
        【解决方案9】:

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

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

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

        【讨论】:

        • 这对我有用 seaborn.swarmplot,但对 seaborn.lmplot 不起作用。使用seaborn.lmplot,我发现sns_plot.savefig("output.png") 的工作方式与Salvatore 的回答一样,但不需要get_figure() 电话。
        • 这适用于 displot 和 seaborn 0.11.2。我可以开始工作的唯一答案!
        【解决方案10】:

        你应该可以直接使用sns_plotsavefig方法。

        sns_plot.savefig("output.png")
        

        为了清楚您的代码,如果您确实想访问 sns_plot 所在的 matplotlib 图,那么您可以直接使用

        fig = sns_plot.fig
        

        在这种情况下,没有您的代码假定的 get_figure 方法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-04
          • 2012-12-04
          • 2015-11-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多