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

标签 python pandas matplotlib histogram seaborn

我有一个名为 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)

enter image description here

但是当我尝试叠加时,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)

enter image description here

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

最佳答案

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

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

关于python - Python中Pandas/Matplotlib中直方图和密度的叠加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41481715/

相关文章:

python - 将参数传递给youtube-dl

python - 将 2 个 CSV 文件与另一个文件中的映射值合并,以逗号分隔

Python/Matplotlib - 更改子图的相对大小

python - 如何向箱线图异常值添加注释

python - Matplotlib:如何在不增加图形大小的情况下增加保存的面积

Python - 子进程 - 如何在 Windows 中调用管道命令?

python - requests.json 和 json.loads() JSONDecodeError : Expecting value: line 1 column 1 (char 0)

python - 这些代码示例中列出了哪些函数?

python - pandas 获取组内值的分布

javascript - 从 node.js 运行 Python 脚本时出现 parseError