Search code examples
pythonpandasmatplotlibplotfacet

Facet barplot with bars are side-by-side in pandas


This works but isn't there a better way to facet barplot with bars are side-by-side in pandas? I feel like there might be a clean way to write using multiindex and subplots argument?

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'group': ['A', 'A', 'B', 'B'], 
                   'name': ['name1', 'name2', 'name3', 'name4'], 
                   '2016': [1, 2, 3, 4], 
                   '2017': [1.2, 2.1, 3.0, 4.9]})    
df.set_index(['name'], inplace=True)

fig, ax = plt.subplots(2)

group_a = df[df.group == 'A']
group_b = df[df.group == 'B']
group_a.plot(kind='bar', rot=0, ax=ax[0])
group_b.plot(kind='bar', rot=0, ax=ax[1])

enter image description here


Solution

  • If you want to do something more than once, it always worth considering the use of a function and a loop. Here, a loop is sufficient.

    groups = df.group.unique()
    
    fig, ax = plt.subplots(len(groups))
    
    for i, group in enumerate(groups):
        df[df.group == group].plot(kind='bar', rot=0, ax=ax[i])
    

    Resulting plot