gpt4 book ai didi

python - 如何将 Seaborn 图保存到文件中

转载 作者:IT老高 更新时间:2023-10-28 21:05:23 25 4
gpt4 key购买 nike

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

enter image description here

我该如何解决这个问题?

最佳答案

以下调用允许您访问该图(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

关于python - 如何将 Seaborn 图保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32244753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com