[英]How to plot a graph with group by?
我有一個像這樣的 dataframe:
quantity fruit
---------------------
1 apple
1 apple
0 apple
1 orange
我想group by
所有水果和 plot 圖對數量為 1 的總百分比進行分組。例如,蘋果有 2/3 = 66.67%,橙子有 1/3 = 33.33%
所以,我想 plot 一個圖表,x 軸上有水果,y 軸上有 %。
嘗試以下操作:
pd.concat([dataframe, colum-you-want-to-group-by], axis=1).groupby('name-of the-column').name-of-the-column.mean().plot(kind='barh').set_xlabel('% TEXT')
如果您已從 dataframe 中拆分列,則上述內容是正確的,如果您不只是像這樣省略concat
:
name-of-your-dataframe.groupby('name-of the-column').name-of-the-column.mean().plot(kind='barh').set_xlabel('% TEXT')
我能夠做到這一點並得到你想要的結果。 看一下這個。
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
res = df.groupby(['fruit']).sum()
res['percentage'] = res['quantity'] / res['quantity'].sum() # add * 100 for percentage
print(res)
ax = res['percentage'].plot(kind='bar', title ="Your Demo Graph", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Fruits", fontsize=12)
ax.set_ylabel("Percentage", fontsize=12)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.