Given the following count plot how do I place percentages on top of the bars?
import seaborn as sns
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
ax = sns.countplot(x="class", hue="who", data=titanic)
For example for "First" I want total First men/total First, total First women/total First, and total First children/total First on top of their respective bars.
Please let me know if my explanation is not clear.
Thanks!
sns.barplot
doesn't explicitly return the barplot values the waymatplotlib.pyplot.bar
does (see last para), but if you've plotted nothing else you can risk assuming that all thepatches
in the axes are your values. Then you can use the sub-totals that the barplot function has calculated for you:produces
An alternate approach is to do the sub-summing explicitly, e.g. with the excellent
pandas
, and plot withmatplotlib
, and also do the styling yourself. (Though you can get quite a lot of styling fromsns
context even when usingmatplotlib
plotting functions. Try it out -- )With the help of cphlewis's solution, I managed to put the correct percentages on top of the chart, so the classes sum up to one.
However, the solution assumes there are 2 options (man, woman) as opposed to 3 (man, woman, child).
Since
Axes.patches
are ordered in a weird way (first all the blue bars, then all the green bars, then all red bars), you would have to split them and zip them back together accordingly.