Home > Software engineering >  geom_text percentages labels : how to do that when using facet_wrap or facet_grid?
geom_text percentages labels : how to do that when using facet_wrap or facet_grid?

Time:10-27

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

CodePudding user response:

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

  • Related