Search code examples
rggplot2pie-chart

Pie chart - How to get the percent text at the right location?


I have issues having the percentage information at the right locations on my pie chart. Could someone very kindly help me on that? Thank you very much!

        #sample dataframe       
        d <- data.frame(facet=c('a','b','c', "d"), value=c('0.46','0.11','0.18', "0.25"))
        d$value <- as.numeric(as.character(d$value))


blank_theme <- 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")
  )

        d$perc <- round(d$value/sum(d$value) * 100,0)
        d$pos <-  cumsum(d$perc) - sapply(d$perc,function(x) cumsum(x)-0.5*x)

        bp <- ggplot(data=d, aes(x="", y=perc, fill=facet))+
          geom_bar(width = 1, stat = "identity") + 
          geom_text(aes(x="", y=pos, label=paste0(perc,"%"))) +
          #geom_text(aes(x="", y=value/4+ c(0, cumsum(value)[-length(value)]), label=percent(value/100))) 
          scale_fill_manual(values = c("a" = "#b2df8a", "b" = "#238b45", "c" = "#636363", "d"="orange"))
        bp

        pie <- bp +  coord_polar("y", start=0) + blank_theme +
          theme(axis.text.x=element_blank())  
        pie

enter image description here


Solution

  • It happens that for some reason ggplot2 goes to the other direction when dealing with labels. Hence, instead using

    d$pos <-  100 - (cumsum(d$perc) - sapply(d$perc, function(x) cumsum(x) - 0.5 * x))
    

    gives

    enter image description here