Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading