问题描述
是否有惯用的方式绘制两个类的要素直方图?在大熊猫中,我基本上想要
Is there a idiomatic way to plot the histogram of a feature for two classes?In pandas, I basically want
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.
我基本上希望在一行熊猫中使用这个matplotlib示例: http://matplotlib.org/examples/pylab_examples/barchart_demo .html
Basically I want this matplotlib example in one line of pandas: http://matplotlib.org/examples/pylab_examples/barchart_demo.html
我以为我错过了一些东西,但也许还没有(可能).
I thought I was missing something, but maybe it is not possible (yet).
推荐答案
df.groupby("class").feature.hist()
怎么样?要查看重叠的分布,您可能需要将alpha=0.4
传递给hist()
.另外,我很想使用内核密度估计值代替df.groupby("class").feature.plot(kind='kde')
的直方图.
How about df.groupby("class").feature.hist()
? To see overlapping distributions you'll probably need to pass alpha=0.4
to hist()
. Alternatively, I'd be tempted to use a kernel density estimate instead of a histogram with df.groupby("class").feature.plot(kind='kde')
.
作为示例,我使用以下命令绘制了虹膜数据集的类:
As an example, I plotted the iris dataset's classes using:
iris.groupby("Name").PetalWidth.plot(kind='kde', ax=axs[1])
iris.groupby("Name").PetalWidth.hist(alpha=0.4, ax=axs[0])
这篇关于根据pandas/matplotlib中的类绘制直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!