Home > other >  Center percentages in pie chart in R
Center percentages in pie chart in R

Time:11-08

I am in the process of creating a pie chart in R using ggplot2. So far everything has worked great, only the percentages don't fit to their corresponding section. Can anyone tell me what could be the reason for this? I have already tried many things but nothing has worked. Many thanks and greetings

datE = data.frame(
  group = c("A","B","C","D"),
  value = c(41,18,30,19)
)

ei <- ggplot(datE, aes(x="", y=value, fill=group)) 
  geom_bar(width = 1, stat = "identity")
pieE <- ei   coord_polar("y")
blank_themeG <- theme_minimal() 
  theme(
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    panel.border = element_blank(),
    panel.grid=element_blank(),
    axis.ticks = element_blank(),
    plot.title=element_text(size=14, face="bold")
  )
pieE   scale_fill_brewer("group")   blank_themeG  
  theme(axis.text.x=element_blank())  
  geom_text(aes(y = value/3   c(0, cumsum(value)[-length(value)]), 
                label = percent(value/100)), size=5) 

resulting pie chart

I tried to change something in geom_text, but it didn't work.

CodePudding user response:

You can simply use position_stack(vjust = 0.5) on the values instead of calculating the position yourself:

pieE   scale_fill_brewer("group")   blank_themeG  
  theme(axis.text.x=element_blank())  
  geom_text(aes(y = value, label = percent(value/100)), size = 5,
            position = position_stack(vjust = 0.5)) 

enter image description here

  • Related