在直方图上添加密度曲线

5
我能够用Python制作直方图,但我无法添加密度曲线,我看到许多代码都使用不同的方法在直方图上添加密度曲线,但我不确定如何在我的代码中实现。
我已经添加了density = true,但是无法在直方图上获得密度曲线。
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
X=df['A']

hist, bins = np.histogram(X, bins=10,density=True)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()

1
请看一下使用seaborn的这个答案:https://dev59.com/kG855IYBdhLWcg3wxHcq#32803224 - DrBwts
2
你需要使用 seaborn 库的 distplot() 或者 histplot() 方法。在最新版本(0.11)中,这些方法名和参数有所变化。注意,np.histogram(..., density=True) 表示直方图将被归一化为总面积等于 1,因此可以共享 y 轴与 kdeplot。 - JohanC
2个回答

5

distplot 已被删除:在将来的 seaborn 版本中会被删除。因此,可使用 histplotdisplot 作为替代。

sns.histplot

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
X = df['A']

sns.histplot(X, kde=True, bins=20)
plt.show()

enter image description here

sns.displot

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
X = df['A']

sns.displot(X, kde=True, bins=20)
plt.show()

enter image description here


distplot已被移除

这里是使用seaborndistplot方法的一种方法。同时,在评论中也提到了:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
X = df['A']

sns.distplot(X, kde=True, bins=20, hist=True)
plt.show()

enter image description here


如何调整密度曲线,使其值不是箱形矩形左侧边缘的顶部,而是其中心(使kde的最大值与bin的最大值重合)? - mins

4
Pandas 也有 kde 绘图功能:
hist, bins = np.histogram(X, bins=10,density=True)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width, zorder=1)

# density plot
df['A'].plot.kde(zorder=2, color='C1')
plt.show()

输出:

在此输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接