geom_text,scale_color_manual中的条件文本颜色

Joh*_*ohn 1 r ggplot2 geom-text

在这里我设置colorRedTRUE文本为红色。但是当我将其设置为时FALSE,颜色仍然是红色。

如何使文本颜色取决于的值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")
Run Code Online (Sandbox Code Playgroud)

Rol*_*and 5

这里有一个重要的教训。始终将标度向量传递到标尺valueslabels标度,以确保预期的映射。

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")
Run Code Online (Sandbox Code Playgroud)