1

I am trying to apply a color scale to a loess line based on a 3rd variable (Temperature). I've only been able to get the color to vary based on either the variable in the x or y axis.

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

This code produces the following plot, but I would like the loess line color to vary based on the temperature variable instead.

enter image description here

I tried using

color = loess(temperature ~ values, a2)

but I got an error of

"Error: Aesthetics must be either length 1 or the same as the data (1000): colour, x, y"

Thank you for any and all help! I appreciate it.

Adela
  • 1,757
  • 19
  • 37
D. Chamberlin
  • 75
  • 1
  • 7
  • Possible duplicate of [R ggplot2 - geom\_smooth with gradient color from a third continuous variable](https://stackoverflow.com/questions/43567212/r-ggplot2-geom-smooth-with-gradient-color-from-a-third-continuous-variable) – Sada93 Feb 14 '19 at 17:42

1 Answers1

2

You can't do that when you calculate the loess with a geom_smooth since it only has access to:

..y.. which is the vector of y-values internally calculated by geom_smooth to create the regression curve" Is it possible to apply color gradient to geom_smooth with ggplot in R?

To do this, you should calculate the loess curve manually with loess and then plot it with 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

The downside of this is that it won't fill in gaps in your data as nicely as geom_smooth

divibisan
  • 11,659
  • 11
  • 40
  • 58