通过分组数据与大熊猫堆积条形图

jus*_*der 2 python plot pandas

让我们假设我有pandas数据框,它有很多功能,我对两个感兴趣.我会打电话给他们feature1,并feature2.

feature1可以有三个可能的值. feature2可以有两个可能的值.

我需要按条形图分组feature1并按行数计算每个值的值feature2.(这样会有三个堆叠,每个堆叠有两个柱子).

怎么做到这一点?

目前我有

import pandas as pd
df = pd.read_csv('data.csv')
df['feature1'][df['feature2'] == 0].value_counts().plot(kind='bar',label='0')
df['feature1'][df['feature2'] == 1].value_counts().plot(kind='bar',label='1')
Run Code Online (Sandbox Code Playgroud)

但这不是我真正想要的,因为它不会叠加它们.

jus*_*der 12

另外,我找到了另一种方法(使用pandas):

df.groupby(['feature1', 'feature2']).size().unstack().plot(kind='bar', stacked=True)

来源: 在熊猫中制作堆积条形图


ron*_*est 5

我不确定如何在matplotlib(熊猫默认的绘图库)中执行此操作,但是如果您愿意尝试使用其他绘图库,则使用Bokeh做到这一点非常容易。

这是一个例子

import pandas as pd
from bokeh.charts import Bar, output_file, show
x = pd.DataFrame({"gender": ["m","f","m","f","m","f"],
                  "enrolments": [500,20,100,342,54,47],
                  "class": ["comp-sci", "comp-sci",
                            "psych", "psych",
                            "history", "history"]})

bar = Bar(x, values='enrolments', label='class', stack='gender',
         title="Number of students enrolled per class",
         legend='top_right',bar_width=1.0)
output_file("myPlot.html")
show(bar)
Run Code Online (Sandbox Code Playgroud)

堆积条形图

  • `bokeh.charts` 现已弃用并删除。你有什么替代方案吗? (2认同)