Search code examples
rpie-chart

Ggplot2 : do not display 0 value in pie chart labels


I'm trying to make a pie chart without displaying the 0 value label and I'm unable to do it.

My data :

group <- factor(c("A","B","C","A","B","C","A","B","C","A","B","C"))
prod <-factor(c("Fong","Fong","Fong","Herb","Herb","Herb","Ins","Ins","Ins","Other","Other","Other"))
quant <- c(0,1,0,2,1,1,0,5,3,8,4,6)

df <- data.frame(group, prod, quant)

My script :

library(ggplot2)
ggplot(df, aes(x="", y=quant, fill=prod))+
  geom_col()+
  coord_polar(theta = "y", start=0)+
  facet_wrap(~group)+
  geom_text(aes(label=quant), position=position_stack(vjust=0.5))

Here, this is the result : Pie chart

Is there any solution to not display the 0 value labels?


Solution

  • You can replace your 0 values with NAs, for example with, dplyr::na_if(0) on your dataframe:

    
    df %>% 
      dplyr::na_if(0) %>% 
    ggplot(aes(x="", y=quant, fill=prod))+
      geom_col()+
      coord_polar(theta = "y", start=0)+
      facet_wrap(~group)+
      geom_text(aes(label=quant), position=position_stack(vjust=0.5))