Colour the x-values and show in legend instead of as ticks, in matplotlib (or seaborn)

…衆ロ難τιáo~ 提交于 2021-01-28 07:16:09

问题


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)

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).


回答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:




回答2:


Directly using pandas:

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




回答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 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([])



来源:https://stackoverflow.com/questions/56395543/colour-the-x-values-and-show-in-legend-instead-of-as-ticks-in-matplotlib-or-se

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!