ggplot黄土线颜色比例,来自第三个变量

时间:2019-02-14 16:35:57

标签: r ggplot2

我试图基于第三个变量(温度)将色标应用于黄土线。我只能根据x或y轴上的变量来改变颜色。

set.seed(1938)

a2 <- data.frame(year = seq(0, 100, length.out = 1000), 
                 values = cumsum(rnorm(1000)), 
                 temperature = cumsum(rnorm(1000)))

library(ggplot2)

ggplot(a2, aes(x = year, y = values, color = values)) + 
  geom_line(size = 0.5)  +
  geom_smooth(aes(color = ..y..), size = 1.5, se = FALSE, method = 'loess') +
  scale_colour_gradient2(low = "blue", mid = "yellow", high = "red", 
                         midpoint = median(a2$values)) +
  theme_bw()

此代码生成以下图,但我希望黄土线颜色根据温度变量而变化。

enter image description here

我尝试使用

color = loess(temperature ~ values, a2)

但我得到

的错误
  

“错误:美学的长度必须为1或与数据(1000)相同:颜色,x,y”

感谢您提供的所有帮助!我很感激。

1 个答案:

答案 0 :(得分:2)

geom_smooth计算黄土时,您不能这样做,因为它只能访问:

  

..y..,它是由geom_smooth内部计算以创建回归曲线的y值的向量”    Is it possible to apply color gradient to geom_smooth with ggplot in R?

为此,您应该使用loess手动计算黄土曲线,然后使用geom_line绘制黄土曲线:

set.seed(1938)
a2 <- data.frame(year = seq(0,100,length.out=1000),
                 values = cumsum(rnorm(1000)),
                 temperature = cumsum(rnorm(1000)))

# Calculate loess curve and add values to data.frame
a2$predict <- predict(loess(values~year, data = a2))


ggplot(a2, aes(x = year, y = values)) + 
    geom_line(size = 0.5)  +
    geom_line(aes(y = predict, color = temperature), size = 2) +
    scale_colour_gradient2(low = "blue", mid = "yellow" , high = "red", 
                           midpoint=median(a2$values)) +
    theme_bw()

enter image description here

缺点是,它不会像geom_smooth那样充实数据中的空白