加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何在seaborn分布图中填充曲线下面积

发布时间:2020-12-20 12:04:35 所属栏目:Python 来源:网络整理
导读:我有两个变量 x = [1.883830,7.692308,8.791209,9.262166]y = [5.337520,4.866562,2.825746,6.122449] 而且我想使用包裹在matplotlib中的seaborn来拟合高斯分布.似乎sns.distplot函数是执行此操作的最佳方法,但我无法弄清楚如何填充曲线下方的区域.救命? fi
我有两个变量

x = [1.883830,7.692308,8.791209,9.262166]
y = [5.337520,4.866562,2.825746,6.122449]

而且我想使用包裹在matplotlib中的seaborn来拟合高斯分布.似乎sns.distplot函数是执行此操作的最佳方法,但我无法弄清楚如何填充曲线下方的区域.救命?

fig,ax = plt.subplots(1)
sns.distplot(x,kde_kws={"shade":True},kde=False,fit=stats.gamma,hist=None,color="red",label="2016",fit_kws={'color':'red'});
sns.distplot(y,color="blue",label="2017",fit_kws={'color':'blue'})

我认为“阴影”参数可能是fit_kws参数的一部分,但我没有得到这个.

另一种选择是使用ax.fill()?

解决方法

是的,fit_kws不支持shade参数,与kde_kws不同.但是正如您猜测的那样,我们可以使用ax.fill_between()填充两条曲线下的区域.我们必须从ax对象及其x-y数据中获取线,然后使用它来填充曲线下的区域.这是一个例子.

import numpy as np
import seaborn as sns
import scipy.stats as stats
import matplotlib.pyplot as plt

x = [1.883830,6.122449]
ax = sns.distplot(x,fit_kws={"color":"red"},label="label 1");
ax = sns.distplot(y,fit_kws={"color":"blue"},label="label 2");

# Get the two lines from the axes to generate shading
l1 = ax.lines[0]
l2 = ax.lines[1]

# Get the xy data from the lines so that we can shade
x1 = l1.get_xydata()[:,0]
y1 = l1.get_xydata()[:,1]
x2 = l2.get_xydata()[:,0]
y2 = l2.get_xydata()[:,1]
ax.fill_between(x1,y1,alpha=0.3)
ax.fill_between(x2,y2,alpha=0.3)

plt.show(block=False)

结果如下所示:

enter image description here

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读