如何使用matplotlib进行盒须图

时间:2016-06-20 22:40:18

标签: python pandas matplotlib

我有

num city    inc pop edu crime   cult
1,0 Moscow  29343,00    8683,00 0,00    10,40   0,00
2,0 Paris    25896,00   17496,00    0,00    10,20   1,00
3,0 London    21785,00  15063,00    0,00    14,20   1,00
4,0 Berlin    20000,00  70453,00    1,00    18,00   1,00

我尝试使用

进行box-whisker绘图
desire_salary = (df[(df['inc'] <= int(salary_people))])
result = desire_salary.pivot_table('city', 'cult', aggfunc='count')
result.plot.boxplot(ax=axarr[1, 1])

但我得AttributeError: 'SeriesPlotMethods' object has no attribute 'boxplot' 怎么了?

1 个答案:

答案 0 :(得分:1)

此处的问题是desire_salary.pivot_table('city', 'cult', aggfunc='count')只选中了一个值cultpivot_table的标准行为是当pivot_table只有一个值/一列时返回series。但是,series对象没有boxplot方法,因此我们必须先将其更改为数据框。

有两种方法可以将系列更改为数据帧:

1)在创建list

之前,在pivot_table参数中输入pivot_table(即使只有一个值)
result = df.pivot_table(index='city', values=['cult'], aggfunc='count')
df2.boxplot()

2)在to_frame()

中创建series后调用pivot_table方法
result = desire_salary.pivot_table(values = 'cult', index = 'city', aggfunc='count')
result.to_frame().boxplot()