Arseniy Krupenin
Arseniy Krupenin

Reputation: 3880

How to do box-whisker plot using matplotlib

I have

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

I try to do box-whisker plot with

desire_salary = (df[(df['inc'] <= int(salary_people))])
result = desire_salary.pivot_table('city', 'cult', aggfunc='count')
result.plot.boxplot(ax=axarr[1, 1])

But I get AttributeError: 'SeriesPlotMethods' object has no attribute 'boxplot' What's wrong?

Upvotes: 2

Views: 1378

Answers (1)

Yarnspinner
Yarnspinner

Reputation: 882

The issue here is that desire_salary.pivot_table('city', 'cult', aggfunc='count') has only one value, cult, selected. The standard behavior of pivot_table is to return a series when the pivot_table has only one value/one column. However, the series object has no boxplot method so we must first change it to a dataframe.

There are two ways of changing your series to a dataframe:

1) Entering a list (even though theres only a single value) into the pivot_table argument before creating the pivot_table

result = df.pivot_table(index='city', values=['cult'], aggfunc='count')
df2.boxplot()

2) Calling the to_frame() method after creating a series in pivot_table

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

Upvotes: 1

Related Questions