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

How to add Plotly multiple surfaces with a for loop in R

我正在 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.94,8.96,8.92),
  c(8.84,8.9,8.82,8.92,8.93,8.91),
  c(8.79,8.85,8.79,8.9,8.94,8.92),
  c(8.79,8.88,8.81,8.9,8.95,8.92),
  c(8.8,8.82,8.78,8.91,8.94,8.92),
  c(8.75,8.78,8.77,8.91,8.95,8.92),
  c(8.8,8.8,8.77,8.91,8.95,8.94),
  c(8.74,8.81,8.76,8.93,8.98,8.99),
  c(8.89,8.99,8.92,9.1,9.13,9.11),
  c(8.97,8.97,8.91,9.09,9.11,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,8.99,8.98,9.18,9.2,9.19),
  c(8.93,8.97,8.97,9.18,9.2,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

您可以在此处查看结果:https://plotly.com/r/3d-surface-plots/

我正在尝试使用以下 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

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