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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21548750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:39:36  来源:igfitidea点击:

Plotting histograms against classes in pandas / matplotlib

pythonmatplotlibplotpandas

提问by Andreas Mueller

Is there a idiomatic way to plot the histogram of a feature for two classes? In pandas, I basically want

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

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

To be in the same plot. I could do

要在同一个情节。我可以

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

but that gives me two separate plots.

但这给了我两个不同的情节。

This seems to be a common task so I would imagine there to be an idiomatic way to do this. Of course I could manipulate the histograms manually to fit next to each other but usually pandas does that quite nicely.

这似乎是一项常见的任务,所以我想有一种惯用的方法来做到这一点。当然,我可以手动操作直方图以使其彼此相邻,但通常Pandas可以很好地做到这一点。

Basically I want this matplotlib example in one line of pandas: http://matplotlib.org/examples/pylab_examples/barchart_demo.html

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

I thought I was missing something, but maybe it is not possible (yet).

我以为我错过了一些东西,但也许这是不可能的(目前)。

采纳答案by jmz

How about df.groupby("class").feature.hist()? To see overlapping distributions you'll probably need to pass alpha=0.4to hist(). Alternatively, I'd be tempted to use a kernel density estimate instead of a histogram with df.groupby("class").feature.plot(kind='kde').

怎么样df.groupby("class").feature.hist()?要查看重叠你可能需要通过发行alpha=0.4hist()。或者,我很想使用核密度估计而不是带有df.groupby("class").feature.plot(kind='kde').

As an example, I plotted the iris dataset's classes using:

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

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

enter image description here

在此处输入图片说明