2

Here I set colorRed to TRUE so the text is red. But when I set it to FALSE, the color is still red.

How to make the text color conditional on the value of colorRed?

library(ggplot2)

ann_text = data.frame(x = 1.5, y = max(mtcars$mpg), LABEL = "TEXT", colorRed = FALSE)

ggplot(mtcars, aes(x = factor(am), y = mpg)) + geom_boxplot() +
  geom_text(data = ann_text, aes(x = x, y = y, label = LABEL, color = colorRed)) + 
  scale_color_manual(values = c('red', 'black'), guide = "none")
zx8754
  • 52,746
  • 12
  • 114
  • 209
John
  • 1,779
  • 3
  • 25
  • 53

1 Answers1

10

There is an important lesson here. Always pass a named vector to values and labels in the scales in order to ensure the intended mapping.

ggplot(mtcars, aes(x = factor(am), y = mpg)) + 
  geom_boxplot() +
  geom_text(data = ann_text, aes(x = x, y = y, label = LABEL, color = colorRed)) +
  scale_color_manual(values = c('TRUE' = 'red', 'FALSE' = 'black'), guide = "none")
zx8754
  • 52,746
  • 12
  • 114
  • 209
Roland
  • 127,288
  • 10
  • 191
  • 288