Search code examples
rplotlyhistogramr-plotly

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)

Suppose I have a dataset, DATA, and I already drew 2D histograms for both variable X and Y. Now I want to plot a 3D histogram of X and Y. Does anyone know how to do it? The description of Plotly with R includes creating 3D histograms, but I can't find the tutorial under either 3D Charts or Histograms. And the wild guess below just gives me a rotated 2D histogram.

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

Solution

  • Below you can find some preliminary ideas for drawing a 3D histogram with plotly.
    See this link to understand how the add_3Dbar function works.

    # 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 
    

    enter image description here