Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making 3D plot in R

Tags:

plot

r

3d

I have two vectors x and y of same length;

x <- c(12,14,14,15,16,18)
y <- c(25,36,32,30,36,42)

and function f

f <- function(a,b) {
sum((y - a - b*x)^2)
}

If a and b are two vectors such that:

a <- seq(from=-5,to=5, by=.1)
b <- seq(from=-2.5, to=7.5, by=.1)

I need to evaluate f for each and every possible pair of a and b so that I could make 3D plot for a, b, and z=f(a,b).

I found outer function but this is not working. Can you please suggest me alternative so that I could achieved desired results?

Thanks

like image 604
Neeraj Avatar asked Mar 21 '26 03:03

Neeraj


2 Answers

In two separated parts, you can use the plot3D package:

library(plot3D)

(1) compute z = f(a, b) for each a, b

### Compute z = f(a, b)
a <- seq(from=-5,to=5, by=.1)
b <- seq(from=-2.5, to=7.5, by=.1)

X <- c(12,14,14,15,16,18)
Y <- c(25,36,32,30,36,42)

f <- function(a,b) {
  sum((Y - a - b*X)^2)
}

m <- expand.grid(a, b)
z <- mapply(f, m$Var1, m$Var2)

(2) Declare a mesh and plot the result upon it:

### Plot3D
M <- mesh(a, b)
x.plot <- M$x
y.plot <- M$y

z.plot <- matrix(z, nrow=nrow(x.plot))

persp3D(x.plot, y.plot, z.plot)

And this generates:

persp3D plot

The results have to be double-check though

like image 71
Jbalberge Avatar answered Mar 23 '26 17:03

Jbalberge


xy = expand.grid(a, b)
#     z = f(xy[,1], xy[,2])
mapply(f, xy$Var1, xy$Var2) # see comment below

The first makes the Cartesian product of a and b:

a = 1:3
b = 4:5
expand.grid(a, b)
# prints (I'm not sure about the row order)
# 1 4
# 1 5
# 2 4
# 2 5
# 3 4
# 3 5
like image 38
Bruno Zamengo Avatar answered Mar 23 '26 16:03

Bruno Zamengo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!