如何将ggplot scale_color_manual与可变值一起使用

时间:2018-10-25 17:34:36

标签: r ggplot2

以下情节(从here借来的示例)在cutscale_color_manual中使用了硬编码的间隔,并且运行良好:

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point(aes(colour = cut(qsec, c(-Inf, 17, 19, Inf))),
             size = 5) +
  scale_color_manual(name = "qsec",
                     values = c("(-Inf,17]" = "black",
                                "(17,19]" = "yellow",
                                "(19, Inf]" = "red"),
                     labels = c("<= 17", "17 < qsec <= 19", "> 19"))

enter image description here

但是,我想使用一个变量来定义这些范围,从而导致图形上没有绘制任何图形:

low <- 17
high <- 19

ggplot(mtcars, aes(wt, mpg)) + 
  geom_point(aes(colour = cut(qsec, c(-Inf, low, high, Inf))),
             size = 5) +
  scale_color_manual(name = "qsec",
                     values = c("(-Inf,low]" = "black",
                                "(low,high]" = "yellow",
                                "(high, Inf]" = "red"),
                     labels = c("<= 17", "17 < qsec <= 19", "> 19"))

enter image description here

我知道问题在于scale_color_manual是如何解释变量的,因为以下方法可以工作(但不允许我定义颜色):

low <- 17
high <- 19

ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(colour = cut(qsec, c(-Inf, low, high, Inf))),
             size = 5)

enter image description here

为什么不起作用?

0 个答案:

没有答案