如何将 Seaborn 图保存到文件中

新手上路,请多包涵

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

在此处输入图像描述

我该如何解决这个问题?

原文由 neversaint 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 737
1 个回答

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

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

正如之前在 这个答案 中看到的那样。

建议的解决方案与 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


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

 fig = myGridPlotObject.fig

原文由 Salvatore Cosentino 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题