30

How can I plot a Python Pandas multiindex dataframe as a bar chart with group labels? Do any of the plotting libraries directly support this? This SO post shows a custom solution using matplotlib, but is there direct support for it?

As an example:

quarter  company
Q1       Blue       100
         Green      300
Q2       Blue       200
         Green      350
Q3       Blue       300
         Green      400
Q4       Blue       400
         Green      450
Name: count, dtype: int64

...can this dataframe be plotted with group labels like this?

Thanks in advance,

Rafi

Community
  • 1
  • 1
rbinnun
  • 1,169
  • 2
  • 10
  • 18
  • The [SO post](https://stackoverflow.com/questions/43545879/bar-chart-with-multiple-labels) refrenced by Goodword below solves this. – rbinnun Jun 16 '17 at 17:53

1 Answers1

65
import pandas as pd

data = pd.DataFrame([
        ('Q1','Blue',100),
        ('Q1','Green',300),
        ('Q2','Blue',200),
        ('Q2','Green',350),
        ('Q3','Blue',300),
        ('Q3','Green',400),
        ('Q4','Blue',400),
        ('Q4','Green',450),
    ], 
    columns=['quarter', 'company', 'value']
)
data = data.set_index(['quarter', 'company']).value

data.unstack().plot(kind='bar', stacked=True)

stacked bar chart from multiindex

If you don't want to stack your bar chart:

data.unstack().plot(kind='bar')

not-stacked bar chart

Goodword
  • 1,565
  • 19
  • 27
  • 1
    Thanks @Goodword , can the labels be grouped as well? like [this chart](https://i.stack.imgur.com/R5PJg.png)? – rbinnun Jun 16 '17 at 12:49
  • Sure. Just don't pass the `stacked=True` argument. Try this instead: `data.unstack().plot(kind='bar')` – Goodword Jun 16 '17 at 14:10
  • 1
    I see now that the labels in the image you sent is a little different than my correction. [This SO post](https://stackoverflow.com/questions/43545879/bar-chart-with-multiple-labels) should help you out with those labels. – Goodword Jun 16 '17 at 14:16
  • Thanks @Goodword , the [SO post](https://stackoverflow.com/questions/43545879/bar-chart-with-multiple-labels) you refrenced did the trick. – rbinnun Jun 16 '17 at 17:51