【问题标题】:How to add Plotly multiple surfaces with a for loop in R如何在R中使用for循环添加多个曲面
【发布时间】:2021-09-07 15:15:03
【问题描述】:

我正在 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

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

【问题讨论】:

    标签: r loops plotly surface


    【解决方案1】:

    你是懒惰评估的受害者。 (参见,例如,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
    

    [注意&lt;&lt;-的用法。]给予

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 2020-08-20
      • 2021-09-28
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      相关资源
      最近更新 更多