How to change colour and position of geom_text for just one bar in a barplot in ggplot2 (R)?

Via conditional logic:

library(ggplot2)
ggplot(data, aes(x = group, y = percentage))+
    theme_bw()+
    geom_bar(stat = 'identity', position = "dodge", fill = "#13449f") +
    geom_text(aes(label = percentage), position = position_dodge(0.9), 
              vjust = ifelse(data$percentage > 3, 1.3, -0.3), 
              colour = ifelse(data$percentage > 3, "white", "black"), 
              size = 6)

1

With group3 == 3.1

2

What is comfortable about this approach:

  • it automatically takes care of values that are big and small
  • you do not need a second data frame or geom

Caveat of this approach:

  • What is hardcoded as > 3 should be calibrated for each visualization. It is possible to automatize that part if you dive deeper into how ggplot2 builds graphs, but it would be overkill for this small example.