Python 从seaborn保存情节

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45569592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:08:01  来源:igfitidea点击:

Saving plot from seaborn

pythonmatplotlibplotseaborn

提问by Roxana Noelia

When I try to save my plot working with seaborn, like this:

当我尝试使用 seaborn 保存我的情节时,如下所示:

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
from pylab import savefig

array = [[100,0], 
        [33,67]]

df_cm = pd.DataFrame(array)

svm = sn.heatmap(df_cm, annot=True,cmap='coolwarm', linecolor='white', linewidths=1)

svm.savefig('svm_conf.png', dpi=400)

I get this error

我收到这个错误

AttributeError                            Traceback (most recent call last)
<ipython-input-71-5c0ae9cda020> in <module>()
----> 1 svm.savefig('svm_conf.png', dpi=400)

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

I have saved some boxplots before, with the same code, but this time, it doesn't work.

我之前用相同的代码保存了一些箱线图,但是这一次,它不起作用。

回答by Adonis

Actually what you would need to do is:

其实你需要做的是:

  • Retrieve the figure from the object returned by sn.heatmap
  • Then and only then save the figure
  • 从返回的对象中检索图形 sn.heatmap
  • 然后才保存图

See the last 2 lines below:

请参阅下面的最后两行:

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
from pylab import savefig

array = [[100,0], 
        [33,67]]

df_cm = pd.DataFrame(array)

svm = sn.heatmap(df_cm, annot=True,cmap='coolwarm', linecolor='white', linewidths=1)

figure = svm.get_figure()    
figure.savefig('svm_conf.png', dpi=400)

回答by ImportanceOfBeingErnest

The command to save the current figure would be

保存当前图形的命令是

plt.savefig()

Because that apparently causes some confusion, here is the full working example:

因为这显然会引起一些混乱,这里是完整的工作示例:

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt

array = [[100,0], 
        [33,67]]

df_cm = pd.DataFrame(array)

svm = sn.heatmap(df_cm, annot=True,cmap='coolwarm', linecolor='white', linewidths=1)

plt.savefig('svm_conf.png', dpi=400)

回答by MosteM

The easiest way would be to use

最简单的方法是使用

plt.savefig('svm_conf.png', dpi=400)

instead of

代替

svm.savefig('svm_conf.png', dpi=400)