1

I have a large df which I've grouped to plot in a bar chart. I made this mock df to show what I mean. (And I had way too much fun creating it...)

my = pd.DataFrame(
{'names': ['Andrea', 'Donna', 'Kelly', 'Brenda', 'Allison', 'Jo', 'Amanda', 'Jane', 'Kerry', 'Abby', 'Elizabeth', 'Haleh'],
'episodes': [ 147, 292, 292, 111, 160, 111, 199, 172, 250, 189, 160,184 ],
'tv-show' : ['Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210',
'Melrose place', 'Melrose place', 'Melrose place', 'Melrose place',
'ER', 'ER', 'ER', 'ER']})
my

And then I grouped and plotted it: my.groupby('tv-show').sum().plot(kind='bar', stacked = True) enter image description here

What I would like is a plot where the names of the tv-shows are in a legend instead of under the x-axis and where the shows have different colours (of course).

Mactilda
  • 393
  • 6
  • 18
  • For each show having a different color, you can check the post: https://stackoverflow.com/questions/18903750/vary-the-color-of-each-bar-in-bargraph-using-particular-value – some_programmer May 31 '19 at 13:33

3 Answers3

1

Try this with sns:

new_df = my.groupby('tv-show').sum().reset_index()

sns.barplot(x='tv-show', y='episodes', 
            hue='tv-show', data=new_df)

Output:

enter image description here

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
1

Directly using pandas:

ax = my.groupby('tv-show').sum().transpose().plot.bar()
ax.set_xticks([])

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
0

Another alternative solution using matplotlib could look something like

import matplotlib.patches as mpatches

fig, ax = plt.subplots(figsize=(8, 6))

# Your dataframe "my" here

ax_ = my.groupby('tv-show').sum().plot(kind='bar', stacked=True, legend=False, ax=ax) 

colors = ['r', 'g', 'b']
handles = []
for col, lab, patch in zip(colors, np.unique(my['tv-show']), ax_.axes.patches):
    patch.set_color(col)
    handles.append(mpatches.Patch(color=col, label=lab))

ax_.legend(handles=handles)    
ax_.set_xticklabels([])

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71