[英]Plot pandas groupby object
I have a groupby object to which I applied value_counts(normalize=True) which yields the following series: 我有一个groupby对象,向其应用了value_counts(normalize = True),它产生以下序列:
Category Reason
25-39 year old Money 0.20
Time 0.10
Interest 0.70
40-54 year old Money 0.50
Time 0.20
Interest 0.30
55+ year old Money 0.70
Time 0.10
Interest 0.20
And I would like to make a bar chart, where x = category, y = values (shown above), and the "Reason" column being used as hue. 我想制作一个条形图,其中x =类别,y =值(如上所示),“原因”列用作色相。 See quick example in paint below: 请参见下面的油漆中的快速示例:
Rather than using groupby()
you could make a pivot table and plot it directly. groupby()
使用groupby()
即可制作数据透视表并直接对其进行groupby()
。 Assuming your value column is called 'Value'
: 假设您的值列称为'Value'
:
from io import StringIO
import pandas as pd
import matplotlib.pyplot as plt
data = StringIO('''Category,Reason,Value
25-39 year old,Money,0.20
25-39 year old,Time,0.10
25-39 year old,Interest,0.70
40-54 year old,Money,0.50
40-54 year old,Time,0.20
40-54 year old,Interest,0.30
55+ year old,Money,0.70
55+ year old,Time,0.10
55+ year old,Interest,0.20''')
df = pd.read_csv(data)
df['Category'] = df['Category'].str.replace(' year old', '')
pvt = df.pivot_table(index='Category', columns='Reason', values='Value')
pvt.plot.bar()
plt.show()
This shows the following graph: 这显示下图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.