Dexter1611
Dexter1611

Reputation: 572

Add density curve on the histogram

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

Upvotes: 7

Views: 16255

Answers (2)

Grayrigel
Grayrigel

Reputation: 3594

distplot has been removed: 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()

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 has been removed

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

enter image description here

Upvotes: 6

Quang Hoang
Quang Hoang

Reputation: 150785

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:

enter image description here

Upvotes: 4

Related Questions