如何在R中使用for循环添加Plotly多个曲面

问题描述

我正在 R 中绘制多个曲面图。这是 Plotly 页面中的一个示例:

z <- c(
  c(8.83,8.89,8.81,8.87,8.9,8.87),c(8.89,8.94,8.85,8.96,8.92),c(8.84,8.82,8.92,8.93,8.91),c(8.79,8.79,8.88,8.95,c(8.8,8.78,8.91,c(8.75,8.77,8.8,8.94),c(8.74,8.76,8.98,8.99),8.99,9.1,9.13,9.11),c(8.97,8.97,9.09,9.11,c(9.04,9.08,9.05,9.25,9.28,9.27),c(9,9.01,9,9.2,9.23,9.2),c(8.99,9.18,9.19),c(8.93,9.18)
)
dim(z) <- c(15,6)
z2 <- z + 1
z3 <- z - 1

fig <- plot_ly(showscale = FALSE)
fig <- fig %>% add_surface(z = ~z)
fig <- fig %>% add_surface(z = ~z2,opacity = 0.98)
fig <- fig %>% add_surface(z = ~z3,opacity = 0.98)

fig

您可以在此处查看结果:

enter image description here

我正在尝试使用以下 R 代码对 3D 数字矩阵执行相同操作:

# Create a tridimensional array
R = 3

v1 = replicate(R,0)
v2 = replicate(R,0)
v3 = replicate(R,0)

AR <- array(c(v1,v2,v3),dim = c(R,R,R))

# 2) Fill the array

for (i in 1:R)
    for (j in 1:R)
        for (k in 1:R)
            AR[i,j,k] <- sample(1:3,1)

#print(AR)
library(plotly)
library(htmlwidgets)


fig <-plot_ly(showscale = FALSE)

#Try to create the fig with a loop

for (k in 1:R)
{                                   # Abre ciclo for.

s <- AR[,k] + 10*k
print(s)

fig <- fig %>% add_surface(z = ~s)

}                                   # Cierra ciclo for.


fig

但只获取最后添加的曲面的图形。你能告诉我错误在哪里吗?

解决方法

您是懒惰评估的受害者。 (例如,请参见 here。] for 循环使用惰性求值,因此您的索引 k 仅在需要求值 fig 时才求值,这发生在您打印 fig。此时,k 等于 R,因此您将获得相同表面的 R 份副本,相互重叠。

您需要force评估。一种方法是使用 lapply,默认情况下会强制求值。

例如

lapply(
  1:R,function(k) {                                   # Abre ciclo for.
    s <- AR[,k] + 10*k
    print(s)
    fig <<- fig %>% add_surface(z = ~s)
  }  
)

# Cierra ciclo for.
fig

[注意 <<- 的使用。] 给予

enter image description here