我有一个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
我想制作一个条形图,其中x =类别,y =值(如上所示),“原因”列用作色相。请参见下面的绘画示例:
答案 0 :(得分:1)
您可以制作一个数据透视表并直接绘制它,而不是使用groupby()
。假设您的值列称为'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()
这显示下图: