如何在 R 中使用 Plotly 制作 3D 直方图?

How to make a 3D histogram with Plotly in R?

library(plotly)

fig1 <- plot_ly(data=DATA, x=~X, name="X",
                type="histogram", histnorm="probability")
fig2 <- plot_ly(data=DATA, x=~Y, name="Y",
                type="histogram", histnorm="probability")

subplot(fig1, fig2)

假设我有一个数据集 DATA,并且我已经为变量 XY 绘制了二维直方图。现在我想绘制 XY3D 直方图 。有谁知道该怎么做? Plotly with R 的描述包括创建 3D 直方图,但我在 3D Charts or Histograms 下都找不到教程。下面的疯狂猜测只是给了我一个旋转的二维直方图。

fig <- plot_ly(data=DATA, x=~X, y=~Y, 
               type="histogram", 
               histnorm="probability"
              ) %>%
              layout(scene=list(xaxis=list(title="X",zeroline=TRUE),
                                yaxis=list(title="Y",zeroline=TRUE),
                                zaxis=list(title="Frequency",zeroline=TRUE)
                               )
                    )

fig

您可以在下面找到使用 plotly 绘制 3D 直方图的一些初步想法。
请参阅此 link 以了解 add_3Dbar 函数的工作原理。

# The matrix with frequencies from a 3 x 4 cross table
z_mtx <- cbind(c(2,4,6,5), c(1,5,9,6), c(2,4,2,3))

# Define a function to add 3D bars
add_3Dbar <- function(p, x,y,z, width=0.4) {
   w <- width
   add_trace(p, type="mesh3d",
     x = c(x-w, x-w, x+w, x+w, x-w, x-w, x+w, x+w),
     y = c(y-w, y+w, y+w, y-w, y-w, y+w, y+w, y-w),
     z = c(0, 0, 0, 0, z, z, z, z),
     i = c(7, 0, 0, 0, 4, 4, 2, 6, 4, 0, 3, 7),
     j = c(3, 4, 1, 2, 5, 6, 5, 5, 0, 1, 2, 2),
     k = c(0, 7, 2, 3, 6, 7, 1, 2, 5, 5, 7, 6),
     facecolor = rep(toRGB(viridisLite::inferno(6)), each = 2)) 
}

# Draw the 3D histogram
fig <- plot_ly()
for (k1 in 1:nrow(z_mtx)) {
  for (k2 in 1:ncol(z_mtx)) {
     fig <- fig %>% add_3Dbar(k1,k2,z_mtx[k1,k2])
  }
}
fig