Search code examples
rggplot2labelgeom-bar

R geom_bar labellng sum of weights


this is my reproducible example

library(ggplot2)
library(dplyr)

mydf<-data.frame(a = rep(c(1:3), each=2),
                 b = c(0.5, 0.5, 1, 1, 1.5, 1.5))

mydf %>% 
  ggplot(aes(x = a)) +
    geom_bar(aes(weight=b))

# and this is a variant getting the same result   
  mydf %>% 
    ggplot(aes(x = a, weight=b)) +
    geom_bar() 

Now I want to add the text labels geom_text() with corresponding values (sum of weights) on top of the bars.

The way I would like to achieve that is by labeling the data without creating a new dataframe (and then using geom_col in combination with geom_text()) but instead following the stream of the code drafted above.

It might be a trivial issue but I'm somehow tied in a knot with the idea to follow a sort of afert_stat approach but without getting to any viable solution so far. I would like to understand how it is possible (and eventually, in fact, if it is!).


Solution

  • You need to use stat = 'count' inside geom_text, and you need to make sure that b is mapped to the weight aesthetic in this layer; either directly or, as in this example, inherited from the main ggplot call to save on typing.

    ggplot(mydf, aes(x = a, weight = b)) +
      geom_bar() +
      geom_text(aes(label = after_stat(count)), stat = 'count', nudge_y = 0.1)
    

    enter image description here


    Or, if this seems a little convoluted, just use b as your y axis values. You can use stat = 'summary' to get the labels in the right place:

    ggplot(mydf, aes(x = a, y = b)) +
      geom_col(position = 'stack') +
      geom_text(aes(label = after_stat(y)), stat = 'summary', 
                fun = 'sum', nudge_y = 0.1)
    

    enter image description here