2

I have the following function

f(x,y) = 2 x^2 + 12 x * y + 7 y^2

And I would like to plot a 3-d graph in R? I am wondering if this is could be done. So I looked on the internet and tried the code below, but nothing was drawn. Could someone point out what is wrong please ?

x <- seq(-100,100,0.1)
y <- seq(-100,100,0.1)
z <- 2*x^2 + 12 * x * y + 7 * y^2

xyz <- data.frame(cbind(x,y,z))
names(xyz) <- c('x', 'y', 'z')
library(lattice)
wireframe(z ~x*y, data = xyz, scales = list(arrows = FALSE), zlab = 'f(x,y)', drape = T)
Nouphal.M
  • 6,304
  • 1
  • 17
  • 28
mynameisJEFF
  • 4,073
  • 9
  • 50
  • 96

1 Answers1

2

Nothing is drawn because your z vector is one-dimensional, defined only at x=y. To expand your data frame, use outer and expand.grid:

 df <- expand.grid(x = x, y = y)
 df$z <- as.vector(outer(x,y, function(x,y) {2*x^2 + 12 * x * y + 7 * y^2}))
 wireframe(z ~ x * y, data = df, scales = list(arrows = FALSE), zlab = 'f(x,y)', drape = T)

enter image description here

tonytonov
  • 25,060
  • 16
  • 82
  • 98