0

Is it possible to create a chart for R Notebook that switches between multiple ggplotly heatmaps by using a dropdown menu?

There is a related post here and here that I have found hard to adapt for the purpose of using heatmaps from ggplotly in Notebook.

For instance, I adapted the use of shiny:

library(shiny)
library(plotly)
library(ggplot2)

# Dummy data
x <- LETTERS[1:20]
y <- paste0("var", seq(1,20))
data <- expand.grid(X=x, Y=y)
data$Z <- runif(400, 0, 5)

data$Z1 <- runif(400, 5, 500)

# Heatmap 
p1=ggplot(data, aes(X, Y, fill= Z)) +  geom_tile() 
p2=ggplot(data, aes(X, Y, fill= Z1)) +  geom_tile() 


ui <-shinyUI(fluidPage(selectInput("selectPlot", "Pair", choices=paste0("p", 1:2)), plotlyOutput("plot")))

server <- shinyServer(function(input,output){      
output$plot <- renderPlotly({
return(get(input$selectPlot)) # get("p1") from the workspace returns the object p1, which is a plotly object
})
})
shinyApp(ui,server)

While it works nicely independently, it does not work inside a chart in Notebooks.

This next option is the most promosing, but the results do no change when changing the dropdown menu.

library(plotly)

df <- data.frame(expand.grid(x=1:20,y=1:20), z = runif(400), j = runif(400), k = rep(0.7, 400), i = rnorm(400,0.6,0.05))

create_buttons <- function(df, z_Val_Names) {
lapply(
z_Val_Names,
FUN = function(var_name, df) {
  button <- list(
    method = 'restyle',
    args = list('fill', list(df[, var_name])),
    label = sprintf('Show %s', var_name)
  )
},
df
)

}

z_Vals <- c( 'z', 'j', 'k', 'i')

p1=ggplot(df, aes(x, y, fill= z)) +  geom_tile() 
p1=ggplotly(p1)
p <-  p1 %>%
layout(
updatemenus = list(
  list(
    y = 1,
    buttons = create_buttons(df, z_Vals)
  )
))
p
Camilo
  • 153
  • 7

1 Answers1

1

I found a solution... not the cleanest but it works.

library(ggplot2)
library(plotly)

df <- data.frame(expand.grid(x=1:20,y=1:20), z = runif(400), j = runif(400), k = runif(400), i = rnorm(400,0.6,0.05))


p <- ggplot(df, aes(x=x, y=y)) +
geom_tile(aes(fill = z))  +
geom_tile(aes(fill = j))  +
geom_tile(aes(fill = k))  +
geom_tile(aes(fill = i))

ggplotly(p, dynamicTicks = TRUE) %>% 
style(visible = TRUE) %>% 
layout(
updatemenus = list(
  list(
    buttons = list(
      list(args = list("visible", list( TRUE, FALSE, FALSE, FALSE)),
           label = "z"),
      list(args = list("visible", list( FALSE, TRUE, FALSE, FALSE)),
           label = "j"),
      list(args = list("visible", list( FALSE, FALSE, TRUE, FALSE)),
           label = "k"),
      list(args = list("visible", list(FALSE, FALSE, FALSE, TRUE)),
           label = "i")
    )
  )
)
)
Camilo
  • 153
  • 7