简体   繁体   English

用熊猫创建按字符串标签分组的条形图

[英]Create bar plot grouped by string label with pandas

I am trying to create a bar plot where the x axis is type and the y axis is price . 我正在尝试创建一个条形图,其中x轴为type ,y轴为price I want to group the bars by each specifict type so I can show bars with a total value 我想按每种规格type对条形进行分组,以便显示总价值的条形

type        price
cookie        1
cookie        3
brownie       2
candy         4
brownie       4

This is what I came up with so far, but it seems to be plotting many different charts 这是我到目前为止提出的,但似乎正在绘制许多不同的图表

ax2 = df_new.groupby([df_new.type]).plot(kind='bar', figsize=(18,7),
                                        color="green", fontsize=13,);
ax2.set_title("Totals", fontsize=18)
ax2.set_ylabel("price", fontsize=18);
ax2.set_xticklabels(df_new['type'])

totals = []

for i in ax2.patches:
    totals.append(i.get_height())
total = sum(totals)

# set individual bar lables using above list
for i in ax2.patches:
    # get_x pulls left or right; get_height pushes up or down
    ax2.text(i.get_x()-.03, i.get_height()+.5, \
            str(round((i.get_height()/total)*100, 2))+'%', fontsize=15,
                color='black')

i think you may just be missing a sum on your group by and the rest is supported out of the box... 我认为您可能只是在您的小组中缺少一笔款项,其余的都可以直接使用...

data = '''type price
cookie 1
cookie 3
brownie 2
candy 4
brownie 4'''

cols, *data = [i.split(' ') for i in data.splitlines()]

import pandas as pd
df = pd.DataFrame(data, columns=cols)
df.price = df.price.astype(int)

ax2 = df.groupby('type').sum().plot.bar()
ax2.set_title("Totals", fontsize=18)
ax2.set_ylabel("price", fontsize=18);

产生

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM