根据pandas/matplotlib中的类绘制直方图

And*_*ler 16 python plot matplotlib pandas

是否有一种惯用的方法来绘制两个类的特征的直方图?在熊猫中,我基本上想要

df.feature[df.class == 0].hist()
df.feature[df.class == 1].hist()
Run Code Online (Sandbox Code Playgroud)

要在同一个情节中.我可以

df.feature.hist(by=df.class)
Run Code Online (Sandbox Code Playgroud)

但这给了我两个独立的情节.

这似乎是一个常见的任务,所以我想有一个惯用的方法来做到这一点.当然,我可以手动操纵直方图以适合彼此,但通常熊猫这样做非常好.

基本上我想在一行熊猫中使用这个matplotlib示例:http://matplotlib.org/examples/pylab_examples/barchart_demo.html

我以为我错过了一些东西,但也许不可能(还).

jmz*_*jmz 15

怎么样df.groupby("class").feature.hist()?要查看重叠的分布,您可能需要传递alpha=0.4给它hist().或者,我很想使用核密度估计而不是直方图df.groupby("class").feature.plot(kind='kde').

例如,我使用以下方法绘制了虹膜数据集的类:

iris.groupby("Name").PetalWidth.plot(kind='kde', ax=axs[1])
iris.groupby("Name").PetalWidth.hist(alpha=0.4, ax=axs[0])
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 什么是`axs`列表应该引用? (3认同)
  • 使用类似`fig,axs = plt.subplots(ncols = 2)`生成的matplotlib轴列表.请参阅文档:http://matplotlib.org/users/recipes.html#easily-creating-subplots (2认同)
  • `axs[1].legend()` 抱怨如果在直方图上使用则没有句柄。对于 KDE 图,您可以传递 `legend=True` (2认同)