I am making plots using ggplot2 in R, and I have trouble combining smoothing and a continuous color scale. More specifically, I would like to draw a bunch of smoothed lines and for each of them, I would like to have their coloring change over the x-axis, such that they are e.g. darkest near their right endpoints. If I were to do this with pointwise linear curves (instead of smoothed lines), I would do something like
d <- data.frame(id = rep(1:100, 10), x = rep(1:10, each = 100),
y = rep(1:10, each = 100) + rnorm(1000),
z = factor(rep(rep(c("a", "b"), each = 10), 500)))
ggplot(d, aes(x = x, y = y, group = id, col = x)) +
geom_line()
which works perfectly fine. However, if I try using a smoother rather than just connecting points, I do not get the same result: All lines simply become black using the following code:
ggplot(d, aes(x = x, y = y, group = id, col = x)) +
geom_line(stat = "smooth", method = "loess")
Any hints as to why this happens and what can be done about it would be very much appreciated! I have seen this post, which suggests that one has to smooth the data before plotting, but I would very much like to do everything in my ggplot()
call.
I have tried two things worth mentioning already. First, using the geom_smooth()
function directly does not make a difference (but does change the default line-color):
ggplot(d, aes(x = x, y = y, group = id, col = x)) +
geom_smooth(se = FALSE, method = "loess")
Secondly, col
does seem to be the correct parameter to target, since when coloring is chosen according to a discrete variable, everything works:
ggplot(d, aes(x = x, y = y, group = id, col = z)) +
geom_line(stat = "smooth", method = "loess")