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:
library(ggplot2)
x = runif(100,-20,20)
y = 2*x+x^2+rnorm(100,0,50)
z = 0.5*x+rnorm(100,0,2)
df = data.frame(x=x,y=y,z=z)
ggplot(data=df,aes(x=x,y=y))+geom_smooth(method='loess', aes(color=z),se=F)
However, the smoothed line is still solid blue.
Using the internal variable "..y.." instead of var3 colors the line with respect to var2.
ggplot(data=df,aes(x=x,y=y))+geom_smooth(method='loess', aes(color=..y..),se=F)
Is there another internal variable to call in order to color the line with respect to var3?
I am able to generate the desired plot with geom_line
, but I would like to have it smoothed instead.
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: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 feedingnewdata=
topredict()
and storing it in a second dataframe, but then you need to also recalculatez
for those newx
values.