Note that there are some explanatory texts on larger screens.

plurals
  1. POCondition a ..count.. summation on the faceting variable
    text
    copied!<p>I'm trying to annotate a bar chart with the percentage of observations falling into that bucket, <em>within</em> a facet. This question is very closely related to this question: <a href="https://stackoverflow.com/questions/3695497/ggplot-showing-instead-of-counts-in-charts-of-categorical-variables">Show % instead of counts in charts of categorical variables</a> but the introduction of faceting introduces a wrinkle. The answer to the related question is to use stat_bin w/ the text geom and then have the label be constructed as so: </p> <pre><code> stat_bin(geom="text", aes(x = bins, y = ..count.., label = paste(round(100*(..count../sum(..count..)),1), "%", sep="") ) </code></pre> <p>This works fine for an un-faceted plot. However, with facets, this sum(..count..) is summing over the entire collection of observations without regard for the facets. The plot below illustrates the issue---note that the percentages do not sum to 100% within a panel. </p> <p><img src="https://i.stack.imgur.com/AZZ3Q.png" alt="enter image description here"></p> <p>Here the actually code for the figure above: </p> <pre><code> g.invite.distro &lt;- ggplot(data = df.exp) + geom_bar(aes(x = invite_bins)) + facet_wrap(~cat1, ncol=3) + stat_bin(geom="text", aes(x = invite_bins, y = ..count.., label = paste(round(100*(..count../sum(..count..)),1), "%", sep="") ), vjust = -1, size = 3) + theme_bw() + scale_y_continuous(limits = c(0, 3000)) </code></pre> <p>UPDATE: As per request, here's a small example re-producing the issue: </p> <pre><code>df &lt;- data.frame(x = c('a', 'a', 'b','b'), f = c('c', 'd','d','d')) ggplot(data = df) + geom_bar(aes(x = x)) + stat_bin(geom = "text", aes( x = x, y = ..count.., label = ..count../sum(..count..)), vjust = -1) + facet_wrap(~f) </code></pre> <p><img src="https://i.stack.imgur.com/id1UY.png" alt="enter image description here"></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload