R 从第三个变量绘制黄土线颜色标度

R 从第三个变量绘制黄土线颜色标度,r,ggplot2,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

我正在尝试根据第三个变量(温度)将色标应用于黄土线。我只能根据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()
但是我犯了一个错误

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


谢谢你的帮助!非常感谢。

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

.y..
这是geom_smooth内部计算的y值向量,用于创建回归曲线”

为此,应使用
黄土
手动计算黄土曲线,然后使用
几何线
绘制:

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()
set.seed(1938)
a2可能的副本
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()