在Python中Pandas/Matplotlib中直方图和密度的叠加

Superimposition of histogram and density in Pandas/Matplotlib in Python

我有一个名为 clean 的 Pandas 数据框,其中包含一列 v,我想为其绘制直方图并叠加密度图。我知道我可以这样画一个在另一个下面:

import pandas as pd
import matplotlib.pyplot as plt

Maxv=200

plt.subplot(211)
plt.hist(clean['v'],bins=40, range=(0, Maxv), color='g')
plt.ylabel("Number")

plt.subplot(212)
ax=clean['v'].plot(kind='density')
ax.set_xlim(0, Maxv)
plt.xlabel("Orbital velocity (km/s)")
ax.get_yaxis().set_visible(False)

但是当我尝试叠加时,y 尺度不匹配(并且我丢失了 y 轴刻度和标签):

yhist, xhist, _hist = plt.hist(clean['v'],bins=40, range=(0, Maxv), color='g')
plt.ylabel("Number")

ax=clean['v'].plot(kind='density') #I would like to insert here a normalization to max(yhist)/max(ax)
ax.set_xlim(0, Maxv)
plt.xlabel("Orbital velocity (km/s)")
ax.get_yaxis().set_visible(False)

有什么提示吗? (附加问题:如何改变密度平滑的宽度?)

不,我试试这个:

ax = clean.v.plot(kind='hist', bins=40, range=(0, Maxv))
clean.v.plot(kind='kde', ax=ax, secondary_y=True)

但是range部分不行,还是左边y轴的问题

根据您的代码,这应该可行:

ax = clean.v.plot(kind='hist', bins=40, normed=True)
clean.v.plot(kind='kde', ax=ax, secondary_y=True)
ax.set(xlim=[0, Maxv])

您甚至可能不再需要 secondary_y

Seaborn 让这一切变得简单

import seaborn as sns
sns.distplot(df['numeric_column'],bins=25)