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

Mat*_*att 5 python matplotlib histogram pandas seaborn

我有一个名为的 Pandas 数据框clean,其中包含一列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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是当我尝试叠加时,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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

一些提示?(附加问题:如何更改密度平滑的宽度?)

Ian*_*anS 5

根据您的代码,这应该有效:

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])
Run Code Online (Sandbox Code Playgroud)

您甚至可能不再需要了secondary_y


Mat*_*att 1

不,我试试这个:

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

但范围部分不起作用,仍然是左侧y轴问题

在此输入图像描述