简体   繁体   English

在R中制作3D绘图

[英]Making 3D plot in R

I have two vectors x and y of same length; 我有两个相同长度的向量x和y;

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

and function f 和功能f

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

If a and b are two vectors such that: 如果a和b是两个向量,那么:

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) . 我需要为每个可能的ab对评估f ,以便我可以为a, b, and z=f(a,b)制作3D图。

I found outer function but this is not working. 我找到了outer功能,但这不起作用。 Can you please suggest me alternative so that I could achieved desired results? 你可以建议我替代,以便我可以取得理想的结果吗?

Thanks 谢谢

In two separated parts, you can use the plot3D package: 在两个独立的部分中,您可以使用plot3D包:

library(plot3D)

(1) compute z = f(a, b) for each a, b (1)计算每个a,b的z = f(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: (2)声明一个网格并在其上绘制结果:

### 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情节

The results have to be double-check though 结果必须仔细检查

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 : 第一个产生ab的笛卡儿积:

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

Here is a very straightforward solution using curve3d from the emdbook package, 这里是使用了非常简单的解决方案curve3demdbook包,

curve3d(f(x,y), from=c(-5,-2.5), to=c(5,7.5), sys3d="persp", theta=90, phi=45)

gives

curve3dpersp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM