在pandas/matplotlib中绘制直方图并按类别分组

24

有没有一种惯用的方法来为两个类别的特征绘制直方图呢?在pandas中,我基本上需要

df.feature[df.class == 0].hist()
df.feature[df.class == 1].hist()

在同一个情节中。我可以做到。

df.feature.hist(by=df.class)

但这样会给我两个单独的图。

这似乎是一项常见任务,所以我想象中应该有一种惯用的方法来完成这个任务。当然,我可以手动操作直方图,使它们相邻,但通常 pandas 可以很好地做到这一点。

基本上,我希望将这个 Matplotlib 示例在一行 Pandas 中实现:http://matplotlib.org/examples/pylab_examples/barchart_demo.html

我以为我错过了什么,但也许现在还不可能。

1个回答

30

如何使用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])

在这里输入图片描述


3
“axs”列表应该指的是什么? - willwest
3
一个由类似于 fig, axs = plt.subplots(ncols=2) 生成的 matplotlib 坐标轴列表。请参阅文档:http://matplotlib.org/users/recipes.html#easily-creating-subplots - jmz
为了获得直方图的一致间距,需要指定 range=[df.PetalWidth.min(), df.PetalWidth.max()] - Piotr Migdal
谢谢!我们如何为箱线图中的颜色获取图例? - nealmcb
将轴对象加一。例如,axs [1] .legend()可能是在那个示例中使用的。 - jmz
2
axs[1].legend() complains about no handles if used on the histogram. For the KDE plot you can pass legend=True - Danielle Madeley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接