我正在尝试创建一个条形图,其中x轴为type
,y轴为price
。我想按每个特定的type
对条形图进行分组,这样我就可以显示总值为
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')
答案 0 :(得分:1)
我想你可能只是错过了你的小组的一笔款项,其余的支持开箱即用......
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);