Problem in showing the Data Labels in the Bar Chart of catplot

114 Views Asked by At

My code is like the below:

import seaborn as sns
from itertools import product

titanic = sns.load_dataset("titanic")

sex_order = titanic['sex'].unique().tolist() 
hue_order = titanic['survived'].unique().tolist()
bar_order = product(sex_order, hue_order)

catp = sns.catplot(data=titanic, kind='count', 
                   x='sex', hue='survived',
                   order = sex_order, 
                   hue_order = hue_order )


spots = zip(catp.ax.patches, bar_order)
for spot in spots:
    total = len(titanic[(titanic['sex']==spot[1][0]) & 
        (titanic['survived']==spot[1][1])])
    height = spot[0].get_height() 
    catp.ax.text(spot[0].get_x()+0.125, height+3, '{:1.0f}'.format(total))

And the output chart is as follows:

catplot

Now my question is that why the number of count for some of bars are shown wrongly. For example, for the red arrow and the yellow arrow. Their number are interchanged with each other.

How can I fix this Problem?

0

There are 0 best solutions below