Multiple data surfaces in a single Plot with buttons

Hi all,

I have also posted this on stackoverflow, but got no response yet. I will try my luck here!

I am making a surface plot with plotly in R and I almost got what I want from it. I want to have an interactive plot with buttons that allows you to switch between different surfaces.

Here is my code.

#simulating random data
x1 <- rnorm(n = 100, mean = 5, sd = 1)
x2 <- rnorm(n = 100, mean = 10, sd = 2.5)

y1 <- rnorm(n = 1000, mean = 4, sd = 3)
y2 <- rnorm(n = 1000, mean = 100, sd = 2.5)

#creating two-dimensional kernal density estimation 
data1 <- kde2d(x = x1, y = x2, n = 25) # n = number of grids)
data2 <- kde2d(x = y1, y = y2, n = 25) # n = number of grids)


p <- plot_ly() %>%
  add_surface(z = data1$z) %>%
  add_surface(z = data2$z)

p <- p %>% layout(
  title = "Button Restyle",
  updatemenus = list(
    list(
      type = "buttons",
      y = 0.8,
      buttons = list(

             list(method = "restyle",
             args = list("visible", c(F,T)),
             label = "group1"),


        list(method = "restyle",
             args = list("visible", c(T,F)),
             label = "group2")))
  ))

The buttons work well, and they switch properly between the different surfaces. My only problem is that for the initial presentation of the plot, I would like the plot either to show the first plot, or show nothing yet. Currently both surfaces are displayed together when I initially run the code.

Any suggestion for how to change this is very welcome!
Thanks in advance!

I received a reply that solved my question: add visible = F to any of your plot functions (add_surface) to hide them initially.

1 Like

Just to add the complete solution:

p <- plot_ly() %>%
  add_surface(z = data1$z, visible=F) %>%
  add_surface(z = data2$z, visible=T)