数据框水平堆积条形图

时间:2020-01-20 17:56:02

标签: python matplotlib

我正在读取movielens用户数据。我想绘制按性别分组的年龄和职业(在两个单独的图中)。但是我得到这个错误:

user_df.groupby(['gender'])['age'].unstack().plot.bar()

AttributeError:无法访问“ SeriesGroupBy”对象的可调用属性“ unstack”,请尝试使用“ apply”方法

我希望该图类似于http://benalexkeen.com/bar-charts-in-matplotlib/中的示例 数据格式如下:

user_id age gender  occupation  zipcode
0   1   24  M   technician  85711
1   2   53  F   other   94043
2   3   23  M   writer  32067
3   4   24  M   technician  43537
4   5   33  F   other   15213

1 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

df.groupby(['occupation'])['user_id'].nunique().plot.bar()

对于性别职业,您都可以执行以下操作:

df.groupby(['occupation','gender'])['user_id'].size().unstack().plot.bar()

enter image description here