python - 如何使用 matplotlib 绘制盒须图

标签 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' 怎么了?

最佳答案

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

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

1) 在创建 pivot_table

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

2) 在pivot_table中创建series后调用to_frame()方法

result = desire_salary.pivot_table(values = 'cult', index = 'city', aggfunc='count')
result.to_frame().boxplot()

关于python - 如何使用 matplotlib 绘制盒须图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37932950/

相关文章:

python - 如何对挂起的 Paho Python Mqtt Single Publish 进行故障排除

python - Beautiful Soup 没有 'get' 完整网页

python - 在没有窗口的情况下绘制和写入图像文件

python - Seaborn 条形图,其中 2 个条形图具有相同标签

python - pandas to_sql 方法给出日期列错误

python - Bottle 的内置 WSGI 服务器与标准 Python wsgiref 服务器模块有何不同?

python - Groupby 求和并计算 python 中的多列

python - 显示半小时间隔的数据框列

python - 在Python中通过Pandas删除时间戳在上一个滑动窗口中的行

python - matplotlib 中可能有奥利奥彩色文本吗?