Search code examples
rggplot2labelgeom-text

'Missing value error/empty data when trying to add labels to a bar chart using geom_text with ggplot2


I'm trying to add labels to my stacked barchart I made with ggplot2, but keep getting an odd error.

I made my table as such:

dd <- read.table(text = "ORIGIN ANIMAL SEX COUNT PR
             1 Canada Dog M 3 37.5
             2 Canada Dog F 5 62.5
             3 Canada Bunny M 3 75
             4 Canada Bunny F 1 25
             5 US Bunny M 9 90
             6 US Bunny F 1 10
             7 US Dog M 3 50
             8 US Dog F 3 50", sep = "", header = TRUE)

and made the figure:

p <-ggplot() + geom_bar(data = dd, aes(y = PR, x = ANIMAL, fill = SEX), 
  stat = "identity", position='stack') + 
  labs( y = "Proportion", x = "") +
  theme_bw() +
  facet_grid( ~ ORIGIN) 

generating:

enter image description here

I'm trying to add COUNT labels to the data, similar to what was being done in this thread:

Showing data values on stacked bar chart in ggplot2

However, when I try to add the labels using:

p + geom_text(aes(labels = COUNT)

I get the error:

Error in if (empty(data)) { : missing value where TRUE/FALSE needed

I've tried explicitly stating all the Boolean arguments for geom_text, but R just ignores the unknown aesthetics.

Is anyone able to explain what I am doing wrong here?

Thank you


Solution

  • You need to move common arguments to the main function, in particular, data and x, y aesthetics.

    library(ggplot2)
    
    p <-ggplot(data = dd, aes(y = PR, x = ANIMAL)) + 
                 geom_col(aes(fill = SEX), position='stack') + 
      labs( y = "Proportion", x = "") +
      theme_bw() +
      facet_grid( ~ ORIGIN)
    
    p + geom_text(aes(label = COUNT), position=position_stack(vjust=0.5), color="white")
    

    Note that geom_col is equivalent to geom_bar with stat="identity". You may also want to adjust the labels to the center of the stacked bars with vjust argument in position_stack()

    here