M. Page
M. Page

Reputation: 2814

pandas bar plot not displaying what I need

I have this pandas DataFrame:

   data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
                 'year': [2000, 2001, 2002, 2001, 2002],
                 'pop': [1.5, 1.7, 2.1, 1.4, 2.9]}
    df = pd.DataFrame(data)

I would like to get something like this inside a Python notebook: enter image description here

Here is what I tried:

import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline

q = p.set_index(['state'])
q['pop'].plot(kind='bar')

which gives this: enter image description here

What am I missing ?

Upvotes: 3

Views: 1699

Answers (1)

Will Pan
Will Pan

Reputation: 282

Try this:

df.pivot(index='year', columns='state', values='pop').plot(kind='bar')

The docs show that the columns of the DataFrame appear as the categories in the plot. DataFrame.pivot reshapes your data by pivoting the unique items in the "state" column as individual columns.

Upvotes: 4

Related Questions