Is there a way to plot a smoothed curve (x=var1, y=var2) and color it with respect to a third continuous variable (z=var3)? I am using the following code:
li
You're on the right track using geom_line
, you just need to use it on pre-smoothed data. Take your dataframe as above, then:
df$predict <- predict(loess(y~x, data = df))
ggplot(df, aes(x = x,y = predict)) +
geom_line(aes(colour = z))
This can generate ugly results if your x
has big gaps; they'll come out as flat segments between points. There are workarounds for that by feeding newdata=
to predict()
and storing it in a second dataframe, but then you need to also recalculate z
for those new x
values.