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

geom_text percentages labels : how to do that when using facet_wrap or facet_grid?

I have this dataframe that I applied ggplot :

df = data.frame(x =rep(1:5,3),
                z = rep(1:3,each = 5),
                y = 100:114 )
df


ggplot(df)+aes(x=x,fill=x,y=y)+
  geom_col(position = 'dodge')+
  facet_wrap(~z)+
  geom_text(aes(label = y),
            position = position_dodge(1),
            vjust=-1,hjust=0,color = 'white' )+
  theme_dark()+
  scale_fill_gradient(low = 'orange',high = 'red')
  

However in my figure I want to change frequencies and make them percentages corresponding to each z variable category.

appreciate the help

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

>Solution :

In cases like this, it’s best to pre-calculate the percentages and then plot that directly:

library(tidyverse)

df %>% 
  group_by(z) %>% 
  mutate(
    y_pct = y / sum(y)
  ) %>% 
ggplot(.)+aes(x=x,fill=x,y=y)+
  geom_col(position = 'dodge')+
  facet_wrap(~z)+
  geom_text(aes(label = sprintf('%0.1f%%', y_pct * 100)),
            position = position_dodge(1),
            vjust=-1,hjust=0,color = 'white' )+
  theme_dark()+
  scale_fill_gradient(low = 'orange',high = 'red')

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