Search code examples
rggplot2geom-text

How to annotate text in a constant vertical place of different geom_col plots


I need to write a function that will make a geom_plot for different data, with different number of columns. I need to add a text annotation in a constant place of plot, no matter how many columns it will have. It will always be on y = 1.02 and I want it to always be aligned to the right. My attempt on a single plot is below:

mtcars %>% 
    mutate(gear = as.factor(as.character(gear))) %>% 
    group_by(gear) %>% summarise(qsec = sum(qsec)) %>% 
    mutate(qsec_index = qsec / mean(qsec)) %>% 
    ggplot() + 
        geom_col(aes(gear, qsec_index)) + 
        geom_hline(aes(yintercept = 1)) + 
        geom_text(aes(x = 3.4, y = 1.02, label = 'Average'))

enter image description here But how can I automate it to be always aligned to the right, no matter if my underlying data have 2, 4, 5 etc. columns?


Solution

  • You can place your annotation according to the number of levels of your x variable. Here we'll use carb instead of gear to demonstrate:

    mtcars %>% 
        mutate(carb = as.factor(as.character(carb))) %>% 
        group_by(carb) %>% summarise(qsec = sum(qsec)) %>% 
        mutate(qsec_index = qsec / mean(qsec)) %>% 
        ggplot() + 
            geom_col(aes(carb, qsec_index)) + 
            geom_hline(aes(yintercept = 1)) + 
            geom_text(aes(x = length(levels(carb)) + .4, y = 1.02, label = 'Average'),
                      hjust = 1, vjust = -1)
    

    and it will still work as expected with gear:

    mtcars %>% 
        mutate(gear = as.factor(as.character(gear))) %>% 
        group_by(gear) %>% summarise(qsec = sum(qsec)) %>% 
        mutate(qsec_index = qsec / mean(qsec)) %>% 
        ggplot() + 
            geom_col(aes(gear, qsec_index)) + 
            geom_hline(aes(yintercept = 1)) + 
            geom_text(aes(x = length(levels(gear)) + .4, y = 1.02, label = 'Average'),
                      hjust = 1, vjust = -1)
    

    enter image description here Created on 2020-04-07 by the reprex package (v0.3.0)