nev*_*int 131 python matplotlib pandas 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()
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
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'
Run Code Online (Sandbox Code Playgroud)
我希望决赛output.png
将会存在,看起来像这样:
我该如何解决这个问题?
Sal*_*ino 175
建议的解决方案与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
Run Code Online (Sandbox Code Playgroud)
以下调用允许您访问该图(Seaborn 0.8.1兼容):
swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...)
Run Code Online (Sandbox Code Playgroud)
正如此答案中所见.
更新: 我最近使用seaborn中的PairGrid对象来生成类似于此示例中的绘图.在这种情况下,由于GridPlot不是一个绘图对象,例如sns.swarmplot,它没有get_figure()函数.可以直接访问matplotlib图
fig = myGridPlotObject.fig
Run Code Online (Sandbox Code Playgroud)
像之前在此帖子中的其他帖子中建议的那样.
Ove*_*ver 97
删除get_figure
并使用sns_plot.savefig('output.png')
df = sns.load_dataset('iris')
sns_plot = sns.pairplot(df, hue='species', size=2.5)
sns_plot.savefig("output.png")
Run Code Online (Sandbox Code Playgroud)
D.M*_*cer 30
上述一些解决方案对我不起作用..fig
我尝试时找不到该属性,我无法.savefig()
直接使用.然而,工作的是:
sns_plot.figure.savefig("output.png")
Run Code Online (Sandbox Code Playgroud)
我是一个较新的Python用户,所以我不知道这是否是由于更新.我想提一下,以防其他人遇到和我一样的问题.
Jad*_*cho 18
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')
Run Code Online (Sandbox Code Playgroud)
更新注意:size
已更改为height
.
Sim*_*ons 13
你应该只能直接使用这种savefig
方法sns_plot
.
sns_plot.savefig("output.png")
Run Code Online (Sandbox Code Playgroud)
为了清楚地了解您的代码,如果您确实想要访问sns_plot
驻留的matplotlib图,那么您可以直接使用它
fig = sns_plot.fig
Run Code Online (Sandbox Code Playgroud)
在这种情况下get_figure
,您的代码假设没有方法.
Sri*_*riK 12
我无法得到其他答案,最终让这个为我工作 matplotlib==3.2.1 。如果您在 for 循环或某种迭代方法中执行此操作,则尤其如此。
sns.scatterplot(
data=df_hourly, x="date_week", y="value",hue='variable'
)
plt.savefig('./f1.png')
plt.show()
Run Code Online (Sandbox Code Playgroud)
请注意,savefig 必须在 show 调用之前。否则将保存空图像。
我使用distplot
和get_figure
成功保存了图片。
sns_hist = sns.distplot(df_train['SalePrice'])
fig = sns_hist.get_figure()
fig.savefig('hist.png')
Run Code Online (Sandbox Code Playgroud)
小智 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')
Run Code Online (Sandbox Code Playgroud)