簡體   English   中英

在R中制作3D繪圖

[英]Making 3D plot in R

我有兩個相同長度的向量x和y;

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

和功能f

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

如果a和b是兩個向量,那么:

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

我需要為每個可能的ab對評估f ,以便我可以為a, b, and z=f(a,b)制作3D圖。

我找到了outer功能,但這不起作用。 你可以建議我替代,以便我可以取得理想的結果嗎?

謝謝

在兩個獨立的部分中,您可以使用plot3D包:

library(plot3D)

(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)聲明一個網格並在其上繪制結果:

### 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)

這會產生:

persp3D情節

結果必須仔細檢查

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

第一個產生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

這里是使用了非常簡單的解決方案curve3demdbook包,

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

curve3dpersp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM