I have this code: (I found somewhere on stackoverflow, just using it to illustrate my idea.)
x<-runif(20)
y<-runif(20)
z<-runif(20, -5,5)
library(rgl)
plot3d(x,y,z)
fit <- lm(z ~ poly(x,2) +poly(y,2) + x:y )
xnew <- seq(min(x), max(x), len=20)
ynew <- seq(min(y), max(y), len=20)
df <- expand.grid(x = xnew,
y = ynew)
df$z <- predict(fit, newdata=df)
surface3d(xnew, ynew, df$z, col="red")
My question is, how do I make the color a gradient of greens above zero, and reds below zero? Am I being clear?
I found this post: Formatting of persp3d plot
Which helps do the gradient, but I cannot figure out how to make it dependent on the positive/negative values of z, and how to restrict it to green and red, respectively.
Thanks for any help!
EDIT:
I tried to do some things below, adding this:
colors<-rep("red", length(df$z))
colors[(df$z > 0)] <- colorRampPalette(c("yellow","green"))(sum(df$z > 0))
colors[(df$z < 0)] <- colorRampPalette(c("red","yellow"))(sum(df$z < 0))
surface3d(xnew, ynew, df$z, col=colors)
Which produced this:
It looks like the gradient is along the wrong axis. It should be yellow near z = 0, getting more red aas z gets more negative, and more green as z gets more positive. But it is not doing that, applying the gradient (seemingly) along the y-axis.
Thoughts?