rplotly

Putting multiple plots on the same page in R?


I wrote this R code which makes a 3d plot at different values of the variable p3.

First, I define all functions:

library(plotly)
library(dplyr)

calculate_b_values <- function(p1, p2, p3, weights) {
  grid <- expand.grid(p1 = p1, p2 = p2)
  grid$B <- (weights$w4 / weights$w2) * weights$w3 * grid$p1 * grid$p2 * p3
  matrix(grid$B, nrow = length(p1), ncol = length(p2))
}

create_surface_plot <- function(p1, p2, z_matrix, p3_value) {
  plot_ly() %>% 
    add_surface(
      z = z_matrix,
      x = p1,
      y = p2,
      colorscale = "Viridis",
      opacity = 0.9
    ) %>% 
    layout(
      scene = list(
        xaxis = list(title = "p1"),
        yaxis = list(title = "p2"),
        zaxis = list(title = "B"),
        aspectratio = list(x = 1, y = 1, z = 0.7)
      ),
      title = paste("Surface Plot with p3 =", p3_value)
    )
}

generate_surface_plots <- function(p_range = seq(0.1, 1, length.out = 20),
                                  p3_values = c(0.1, 0.4, 0.7, 1.0),
                                  weights = list(w1 = 10, w2 = 5, w3 = 3, w4 = 8)) {
  plot_list <- list()
  for (i in seq_along(p3_values)) {
    p3_fixed <- p3_values[i]
    z_matrix <- calculate_b_values(p_range, p_range, p3_fixed, weights)
    plot_list[[i]] <- create_surface_plot(p_range, p_range, z_matrix, p3_fixed)
  }
  names(plot_list) <- paste0("p3_", p3_values)
  return(plot_list)
}

Then, I call the functions to make all 4 plots:

weights <- list(w1 = 10, w2 = 5, w3 = 3, w4 = 8)
p_vals <- seq(0.1, 1, length.out = 20)
p3_values <- c(0.1, 0.4, 0.7, 1.0)

plots <- generate_surface_plots(p_vals, p3_values, weights)

plots[[1]]
plots[[2]]
plots[[3]]
plots[[4]]

I want to display all 4 plots on the same page. This seems like it can be done using the subplot feature (https://plotly.com/r/subplots/):

plots <- generate_surface_plots(p_vals, p3_values, weights)

combined_plot <- subplot(
  plots[[1]], plots[[2]],
  plots[[3]], plots[[4]],
  nrows = 2, 
  titleX = TRUE,
  titleY = TRUE,
  margin = 0.05
)

combined_plot <- combined_plot %>%
  layout(
    title = list(
      text = "Surface Plots at Different p3 Values",
      font = list(size = 16)
    )
  )

combined_plot

But this is putting them all on the same plot:

enter image description here

How can I place all 4 plots separately on the same page, e.g.

enter image description here


Solution

  • You can use htmltools as a workaround. https://github.com/rstudio/htmltools

    library(htmltools)
    
    browsable(
      tagList(
        plots[[1]],
        plots[[2]],
        plots[[3]],
        plots[[4]]
      )
    )