【问题标题】:Pandas plotting incorrectly sorts the binned values on the graph熊猫绘图错误地对图表上的分箱值进行排序
【发布时间】:2015-08-23 04:06:47
【问题描述】:

我正在使用 Pandas 绘制一个 DataFrame,其中包含三种类型的列:兴趣、性别和经验点。

我想将体验点分箱到特定范围内,然后按分箱值、兴趣和性别对 DataFrame 进行分组。然后,我想按兴趣绘制特定性别(例如:男性)的计数。

使用下面的代码,我能够得到我想要的图,但是,Pandas 错误地对 x 轴上的分箱值进行了排序(请参阅附图的我的意思)。

请注意,当我打印我的 DataFrame 时,分箱值的顺序正确,但在图中,分箱值的排序不正确。

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
...

我的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import random

matplotlib.style.use('ggplot')


interest = ['Swim','Bike','Hike']
gender = ['Male','Female']
experience_points = np.arange(0,200)

df = pd.DataFrame({'Interest':[random.choice(interest) for x in range(1000)],
                   'Gender':[random.choice(gender) for x in range(1000)],
                   'Experience Points':[random.choice(experience_points) for x in range(1000)]})

bins = np.arange(0,136,8)
exp_binned = pd.cut(df['Experience Points'],np.append(bins,df['Experience Points'].max()+1))

exp_distribution = df.groupby([exp_binned,'Interest','Gender']).size()

# Printed dataframe has correct sorting by binned values 
print exp_distribution 

#Plotted dataframe has incorrect sorting of binned values 
exp_distribution.unstack(['Gender','Interest'])['Male'].plot(kind='bar') 

plt.show()

尝试的故障排除步骤:

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

仅按分箱值分组,然后绘制确实可以解决问题,但是我无法按兴趣或性别分组。例如以下作品:

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

【问题讨论】:

  • 也许可以试试plot(kind='bar', sort_columns=True)
  • sort_columns=True 不起作用。

标签: python pandas matplotlib plot


【解决方案1】:

unstack() 乱序了,要恢复索引序。您可能需要为此提交错误报告。

解决方法:

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

【讨论】:

  • 非常感谢您的回答。我为我工作!我想更正你的答案,因为它有一个错字:exp_distribution.unstack(['Gender','Interest']).ix[exp_distribution.index.get_level_values(0).unique()]['Male'].plot(kind='bar')
  • 谢谢,抱歉。
猜你喜欢
  • 2013-10-28
  • 2014-03-21
  • 2022-01-20
  • 2023-03-28
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
相关资源
最近更新 更多