pandas 在直方图上添加密度曲线

jhiyze9q  于 2023-05-27  发布在  其他
关注(0)|答案(2)|浏览(170)

我可以在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()
nimxete2

nimxete21#

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

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

jc3wubiy

jc3wubiy2#

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

输出:

相关问题