我使用以下代码生成了 Seaborn 累积分布图:
AlphaGraphCum = sns.distplot(dfControl["alpha"],
hist_kws={'cumulative': True},
kde_kws={'cumulative': True}, rug=False, hist=False);
sns.distplot(dfGoal["alpha"],
hist_kws={'cumulative': True},
kde_kws={'cumulative': True, 'linestyle':'--'}, rug=False, hist=False);
sns.distplot(dfGraph["alpha"],
hist_kws={'cumulative': True},
kde_kws={'cumulative': True, 'linestyle':':'}, rug=False, hist=False);
sns.distplot(dfGoalGraph["alpha"],
hist_kws={'cumulative': True},
kde_kws={'cumulative': True, 'linestyle':'-.'}, rug=False, hist=False)
AlphaGraphCum.set(xlabel='Alpha')
AlphaGraphCum.set(ylabel='Cumulative Probability')
#AlphaGraphCum.set_xlim(-1,1)
该图的 x 轴范围为 -2 到 +2。然而,当我调查数据时,最小值为-1,最大值为+1。因此,我尝试使用以下方法限制轴:
AlphaGraphCum.set_xlim(-1,1)
我在上面的例子中注释掉了。然后,x 轴被正确限制在 -1 和 +1 之间。然而,对于 x=+1,没有一条线显示 y 值 1.0,它们应该显示 1.0,因为 +1 是最大值,因此累积概率应等于 1.0。
有谁知道为什么情况并非如此?任何提示将不胜感激。谢谢!
最佳答案
distplot
Seaborn 中使用 kde
(Kernel density estimation) 为您提供数据集的近似密度。它假设数据点周围有小的“微内核”,并将它们相加以创建一个整体的“宏内核”。因此,min
和 max
周围的内核肯定会超出限制,因为边缘上的数据点(min
和 max
code>) 是“微内核”的中心。 (注意:术语“微/宏内核”是我刚刚为了解释而编造的。)
假设我们的数据范围从 -10
到 10
,如下所示。
import numpy as np
import pandas as pd
df = pd.DataFrame().assign(a=np.random.randint(-10, 11, 100))
print(df.a.min(), df.a.max())
Out:
-10 10
如果我们使用默认设置绘制 distplot
(其中 kde
为 True
),
import seaborn as sns
sns.distplot(df.a)
它显示了介于 -10
和 10
之间的 直方图
以及近似值 kde
都显示了该直方图(当然,由于上述原因,kde
跨越了 min
和 max
限制)。
现在,如果您想获得累积密度,则 distplot
根据 kde
计算它,如下所示:
sns.distplot(df.a, kde_kws={'cumulative': True})
此时请注意,第一张图中的kde
(蓝线)和第二张图中的累积kde
(蓝线)的两个尾部是对应的。
您可能想知道尾部是否完全对应,因为第一个图和第二个图之间的 y 尺度不同,因此如果我们放大第二个图的 y 轴,它如下所示。
import matplotlib.pyplot as plt
sns.distplot(df.a, kde_kws={'cumulative': True})
plt.ylim([0, 0.07])
现在第一张图和第三张图看起来很相似,但唯一的区别是第一张图是kde
,而第三张图是累积kde
。
长话短说,您绘制的是基于kde
的“近似累积密度”。这就是为什么它的分布(和累积分布)比实际数据(直方图)更广泛。
希望这有帮助。
编辑:添加了累积kde
与累积历史
sns.distplot(df.a,
hist_kws={'cumulative': True},
kde_kws={'cumulative': True, 'linestyle':'-.'},
bins=100)
关于python - Seaborn 分布图 : Data does not match probabilities,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52054168/