Search code examples
rggplot2geom-text

What should be my geom_text aesthetics for y in my ggplot2 codes in this context?


I have the following ggplot2 codes running in RStudio:

p2 <- ggplot(subset(df1,LEVEL %in% c("FM")),aes(x=los_group)) +
    ggtitle("FM: % of Respondents by Length of Service") + xlab("LOS Group") +
    geom_bar(aes(y = 100*(..count..)/sum(..count..)), width = 0.5, fill="steelblue") + 
    ylab("Percentage") +
    geom_text(position=position_dodge(width=0.9), hjust= 1.5, 
    vjust=0.5, angle = 90, color="white", fontface="bold", size=6)+
    coord_flip() + 
    theme_minimal()

p2

I want to insert the percentage values (with the % sign) inside the bars (at the top end). I am stuck at specifying the y aesthetics in my geom_text codes.

Currently, I am getting the following error message:

Error: geom_text requires the following missing aesthetics: y, label

Solution

  • Here's an example using standard data, since we don't have your df1.

    When I'm using a calculation in multiple places, it's often easiest to calculate it prior to ggplot and pipe it in, where it will be interpreted as the first (ie data) term of the ggplot call.

    library(tidyverse)
    
    # Calculate share of counts per cylinder, and pipe that into ggplot
    mtcars %>%
      count(cyl = as.factor(cyl)) %>%
      mutate(share = n / sum(n)) %>%
    
      # Declare global x, y, and label mapping. If not specifically specified
      #   in subsequent `geoms`, they will adopt these. 
      ggplot(aes(x=cyl, y = share, label = scales::percent(share, accuracy = 1))) +
      ggtitle("FM % of Respondents by Length of Service") + 
      xlab("LOS Group") +
      geom_col(width = 0.8, fill="steelblue") + 
      ylab("Percentage") +
      geom_text(position=position_dodge(width=0.9), hjust= 0.5, 
                vjust=-0.5, angle = 90, color="white", fontface="bold", size=6) +
      coord_flip() + 
      theme_minimal()
    

    enter image description here