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

2024-05-16 18:39:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个条形图,其中x轴是type,y轴是price。我想按每个特定的ttype对条形图进行分组,这样就可以用一个总值来显示条形图

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

这是我到目前为止提出的,但它似乎绘制了许多不同的图表

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')

Tags: dfnewgetcookietypebarpricecolor
1条回答
网友
1楼 · 发布于 2024-05-16 18:39:00

我想你可能只是错过了一个金额对你的小组,其余的是支持的开箱即用

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);

which yields

相关问题 更多 >