Skip to content Skip to sidebar Skip to footer

Colour The X-values And Show In Legend Instead Of As Ticks, In Matplotlib (or Seaborn)

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': ['An

Solution 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

Solution 2:

Directly using pandas:

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

enter image description here

Solution 3:

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 inzip(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

Post a Comment for "Colour The X-values And Show In Legend Instead Of As Ticks, In Matplotlib (or Seaborn)"