John John - 27 days ago 6
R Question

Conditional text color in geom_text, scale_color_manual

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")

Answer

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")