2

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?

elena.kim
  • 930
  • 4
  • 12
  • 22
  • 2
    It is looped in the numerical annotations, but isn't the order Male, Male, Female, Female? – r-beginners May 18 '21 at 06:34
  • Yes, that is right. – Amir Mollaei May 18 '21 at 06:43
  • 1
    To get the correct order instead of looping through `ax.patches` you can loop through `ax.containers` as there is one container per hue. You can call the new `ax.bar_label(ax.container_i)` which takes care of positioning the correct labels. – JohanC May 18 '21 at 10:18
  • Thanks JohanC. Excuse me, but I don't get the code. Do mean that my code has to change as follows? `spots = zip(catp.ax.containers, bar_order) for spot in spots: total = len(titanic[(titanic['sex']==spot[1][0]) & (titanic['survived']==spot[1][1])]) catp.ax.bar_label(ax.container_i, '{:1.0f}'.format(total))` I get the below error AttributeError: 'AxesSubplot' object has no attribute 'bar_label' – Amir Mollaei May 18 '21 at 10:53
  • 1
    Well, it's a **new** function. You need the latest matplotlib (3.4.2). – JohanC May 18 '21 at 11:17
  • See also [Bar labels in matplotlib seaborn](https://stackoverflow.com/questions/67112449/bar-labels-in-matplotlib-seaborn) – JohanC May 18 '21 at 11:22

0 Answers0