Search code examples
r3dplotlyheatmap

3 simple 2d slice in plotly as a heatmap with data from a formula in 3d


How can I have 3 2-Dimensional slices (x, y; x, z; y, z) in a 3-Dimensional coordinate system which are heatmaps. Each square in the slices should have a color which is given by the output from a formula. So it should look like this but in plotly or R and with specifically generated data for the colors (not randomized): source - python example

enter image description here


Solution

  • You can use plotly in R to draw surface plots, but as far as I can tell the surfaces will always be interpolated:

    Suppose your x, y and z outputs are given by three different functions:

    fun1 <- function(x, y) {
      sqrt(x^2 + y^2)
    }
    
    fun2 <- function(x, y) {
      rnorm(seq_along(x))
    }
    
    fun3 <- function(x, y) {
      x + y
    }
    

    Then you can create the necessary outputs by doing:

    xvals <- seq(0.01, 1, 0.01)
    yvals <- seq(0.01, 1, 0.01)
    
    df <- expand.grid(x = xvals, y = yvals)
    df$f1 <- c(outer(xvals, yvals, fun1))
    df$f2 <- c(outer(xvals, yvals, fun2))
    df$f3 <- c(outer(xvals, yvals, fun3))
    
    df$f1 <- ave(df$f1, floor(df$x * 10)/10, floor(df$y * 10)/10)
    df$f2 <- ave(df$f2, floor(df$x * 10)/10, floor(df$y * 10)/10)
    df$f3 <- ave(df$f3, floor(df$x * 10)/10, floor(df$y * 10)/10)
    
    library(plotly)
    
    
    plot_ly(df) %>%
     add_surface(z = matrix(0.75, 100, 100), x=matrix(df$x, 100, 100), 
                 y = matrix(df$y, 100, 100), colorscale = 'Rainbow',
                 surfacecolor = ~matrix(df$f1, 100, 100)) %>%
      add_surface(z = matrix(df$y, 100, 100), x = matrix(df$x, 100, 100), 
                  y = matrix(0.5, 100, 100), colorscale = 'Rainbow',
                  surfacecolor = ~matrix(df$f2, 100, 100)) %>%
      add_surface(z = ~matrix(df$y, 100, 100), x = matrix(0.5, 100, 100), 
                  y = matrix(df$x, 100, 100), colorscale = 'Rainbow',
                  surfacecolor = ~matrix(df$f3, 100, 100))
    

    enter image description here