在直方图上添加密度曲线

2024-06-17 09:10:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我能用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()

Tags: 方法代码truedfnpplt直方图density
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()

输出:

enter image description here

这里是一种使用seaborn^{}方法的方法。此外,评论中提到:

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

但是,distplot将是removed in a future version of seaborn。因此,替代方法是使用^{}^{}

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

相关问题 更多 >