Pandas绘图错误地对图形上的二进制值进行排序

2024-09-24 22:32:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Pandas绘制了一个包含三种类型列的数据框:兴趣、性别和经验点。在

我想将体验点划分为特定的范围,然后根据绑定的值、兴趣和性别对数据帧进行分组。然后我想按兴趣绘制特定性别(例如:男性)的计数。在

使用下面的代码,我可以得到我想要的图,但是Pandas在x轴上错误地排序了bined值(见我的意思)。在

enter image description here

请注意,当我打印数据帧时,二进制值的顺序是正确的,但在图形中,二进制值的排序不正确。在

Experience Points  Interest  Gender
(0, 8]             Bike      Female     9
                             Male       5
                   Hike      Female     6
                             Male      10
                   Swim      Female     7
                             Male       7
(8, 16]            Bike      Female     8
                             Male       3
                   Hike      Female     4
                             Male       7
                   Swim      Female    10
                             Male       4
(16, 24]           Bike      Female     4
                             Male       6
                   Hike      Female    10
...

我的代码:

^{pr2}$

尝试的故障排除步骤:

使用plot(kind='bar',sort_columns=True)并不能解决问题

仅按二进制值分组,然后再进行绘图确实解决了这个问题,但我无法按兴趣或性别分组。例如,以下工作:

exp_distribution = df.groupby([exp_binned]).size()
exp_distribution.plot(kind='bar') 

Tags: 数据代码pandas排序plot二进制绘制male
1条回答
网友
1楼 · 发布于 2024-09-24 22:32:58

unstack()弄乱了顺序,必须恢复索引顺序。您可能需要为此提交一个错误报告。在

解决方法:

exp_distrubtion.unstack(['Gender','Interest']).ix[exp_distrubtion.index.get_level_values(0).unique(),
                                                  'Male'].plot(kind='bar') 

enter image description here

相关问题 更多 >