Search code examples
rggplot2pie-chartpercentage

How to plot labels on top of pie charts --> Why pie chart disappears when adding label string?


I do not understand why when adding the labels of the string on the pie chart, the pie chart compresses/disappears. Why is this possible and how can I change it?

library(ggplot2)
library(viridis)
df <- data.frame('Fruit'=c("Apple", "Apple","Pear","Pear", "Coconut","Coconut"), 'Colour'=c("Blue", "Yellow","Blue", "Yellow","Blue", "Yellow"), 'Abundance'=c(57.81,42.19,59.89,40.11,41.73,58.27))

ggplot(df, aes(x = "", y = Abundance, fill = Colour)) + 
  geom_bar(stat = "identity", width = 1, position = position_fill(), colour="black") +
  coord_polar(theta = "y")+
  facet_wrap(~ Fruit, ncol=3)+
  theme_void() +
  scale_fill_viridis(discrete= TRUE)+
geom_text(aes(label = ifelse(Abundance == 0, "", paste0(Abundance, "%"))),
          position = position_stack(vjust = 0.5))

This is before adding the geom_text:

enter image description here

And this is once I add the geom_text:

enter image description here


Solution

  • You could use geom_col instead of geom_bar with stat="identity" and position=position_fill() like this:

    library(ggplot2)
    library(viridis)
    
    ggplot(df, aes(x = "", y = Abundance, fill = Colour)) + 
      geom_col(colour = 'black') +
      coord_polar(theta = "y")+
      facet_wrap(~ Fruit, ncol=3)+
      theme_void() +
      scale_fill_viridis(discrete= TRUE)+
      geom_text(aes(label = ifelse(Abundance == 0, "", paste0(Abundance, "%"))),
                position = position_stack(vjust = 0.5))
    

    Created on 2023-05-31 with reprex v2.0.2

    If you want to use geom_bar you should use position = "position_stack() instead of position_fill since your bars are actually stacked like this:

    geom_bar(stat = 'identity', position = position_stack())