Group Bar Chart with Seaborn/Matplotlib

NumenorForLife picture NumenorForLife · Apr 14, 2016 · Viewed 9.1k times · Source

My goal is to create a grouped bar chart like the one below, using a pandas DataFrame that is grouped by two variables "Alpha" and "Beta." Group Bar Chart

xl2 = xl.groupby(['Alpha','Beta']).median()

When I tried this, a KeyError was thrown on 'Alpha'

import seaborn as sns
sns.barplot(x=['Alpha', 'Beta'], y=xl2['Gamma'])

My hope was to pass in a list of x values to index on ('Alpha' and 'Beta'), and graph the associated 'Gamma." The documentation for the seaborn.barplot function doesn't provide any group bar chart examples.

Thanks for your help!

Answer

Greg picture Greg · May 27, 2016

You can use ggplot for this

from ggplot import *
import pandas as pd
import numpy as np

df = pd.DataFrame({
    "x": np.random.choice(range(2001, 2008), 250),
    "w": np.random.uniform(50, 400, 250),
    "cat": np.random.choice(["A", "B", "C", "D", "E"], 250)
})

print ggplot(df, aes(x='x', weight='w', fill='cat')) + geom_bar() + theme_bw()

ggplot grouped bar