Add density curve on the histogram

早过忘川 提交于 2021-01-04 06:41:49

问题


I am able to make histogram in python but I am unable to add density curve , I see many code which are using different ways to add density curve on histogram but I am not sure how to get on my code

I have added density = true but not able to get density curve on histogram

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:


Here is an approach using distplot method of seaborn. Also, mentioned in the comments:

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

However, distplot will be removed in a future version of seaborn. Therefore, alternatives are to use histplot and displot.

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




回答2:


Pandas also has kde plot:

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

Output:



来源:https://stackoverflow.com/questions/64467644/add-density-curve-on-the-histogram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!