[英]Create bar plot grouped by string label with pandas
我正在嘗試創建一個條形圖,其中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')
我認為您可能只是在您的小組中缺少一筆款項,其余的都可以直接使用...
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.