【问题标题】:Add density curve on the histogram在直方图上添加密度曲线
【发布时间】:2021-02-04 14:36:32
【问题描述】:

我可以在 python 中制作直方图,但无法添加密度曲线,我看到许多代码使用不同的方式在直方图上添加密度曲线,但我不确定如何使用我的代码

我添加了密度 = 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()

【问题讨论】:

  • 您需要 seaborn 的 distplot()histplot()。在最新版本 (0.11) 中,函数名称和参数发生了一些变化。请注意,np.histogram(..., density=True) 表示直方图将被归一化,使得总面积总和为 1,因此它可以与 kdeplot 共享 y 轴。

标签: python pandas numpy matplotlib seaborn


【解决方案1】:

这是一种使用seaborndistplot 方法的方法。此外,在 cmets 中提到:

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()

但是,distplot 将是 removed in a future version of 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()

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()

【讨论】:

  • 如何调整密度曲线,使其值不是bin矩形左边缘的顶部,而是它的中心(和kde和bin的最大值重合)?
【解决方案2】:

熊猫也有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()

输出:

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多