Armonia
Armonia

Reputation: 53

Y axis labels are not ordered like the bars in seaborn

I have a data frame called general_stats that has information about YouTube channels like title, number of subscribers and such. I want to plot the channels name against the number of subscribers for each in a bar plot using seaborn. but when I try to order the bars by the number of subs they get ordered but the y axis labels stay the same.

This is before ordering :

fprop = fm.FontProperties(fname='FontsKR/NotoSansCJKtc-Regular.otf')

names = general_stats['Channel_name']
subs = general_stats['Subscribers_Count']

fig = sns.barplot(x=subs, y=names, palette ='Blues_r').set_yticklabels(labels = 
names,fontproperties=fprop, fontsize=12)
fig ;

which gives me this result :

before

and this is after ordering :

fprop = fm.FontProperties(fname='FontsKR/NotoSansCJKtc-Regular.otf')

names = general_stats['Channel_name']
subs = general_stats['Subscribers_Count']

fig = sns.barplot(x=subs, y=names, palette ='Blues_r', order= 
general_stats.sort_values('Subscribers_Count', 
ascending=False).Channel_name).set_yticklabels(labels = names,fontproperties=fprop, 
fontsize=12)
fig;

and it gives me this plot:

after

as you can see, the bars got ordered but the y axis labels stayed the same. how can i order them with the bars without ordering the data frame itself ? i have to set the ytick labels myself so i can display the chinese/korean/japanese characters. maybe its because i set the yticklabels after the bars were ordered ? how can i bypass this cause i do need the font that i am using !

Upvotes: 2

Views: 376

Answers (1)

Arne
Arne

Reputation: 10545

Yes, this happens because you set the y tick labels after the bars were ordered, so you need to use the sorted names there as well. Try this:

fprop = fm.FontProperties(fname='FontsKR/NotoSansCJKtc-Regular.otf')

names = general_stats['Channel_name']
subs = general_stats['Subscribers_Count']

names_ordered = general_stats.sort_values('Subscribers_Count', 
                                          ascending=False).Channel_name

ax = sns.barplot(x=subs, y=names, palette='Blues_r', 
                 order=names_ordered)
ax.set_yticklabels(labels=names_ordered, fontproperties=fprop, fontsize=12)  

Upvotes: 2

Related Questions