Drill Down Reporting with Shiny using ggplotly

I am trying to replicate the below code from a previous post using ggplot instead of plotly but the drill down creates an empty plot. Is it possible to achieve the same drill down bar graph by wrapping with ggplotly?

https://forum.posit.co/t/whats-the-best-way-to-drill-down-a-plot/30221

Code

library(shiny)
library(dplyr)
library(gapminder)

ui <- fluidPage(plotlyOutput("pop"), uiOutput("back"))

server <- function(input, output, session) {
  
  selections <- reactiveVal()
  
  # show population by continent by default, but if there is a selected continent
  # show population by country within that continent
  output$pop <- renderPlotly({
    nSelections <- length(selections())
    if (nSelections == 0) {
      df <- gapminder %>% 
        group_by(continent) %>%
        summarise(pop = sum(as.numeric(pop)))
      
      ggplotly(ggplot(df, aes(pop,continent)) +
        geom_col()
        )
      
    } else {
      df <- gapminder %>%
        filter(continent %in% selections()) %>%
        group_by(country) %>%
        summarise(pop = sum(as.numeric(pop)))
      
      ggplotly(ggplot(df, aes(pop,country)) +
                 geom_col()
               )
    }
  })
  
  observeEvent(event_data("plotly_click"), {
    new <- event_data("plotly_click")$x
    old <- selections()
    selections(c(old, new))
  })
  
  # populate back button if category is chosen
  output$back <- renderUI({
    if (length(selections())) 
      actionButton("clear", "Back", icon("chevron-left"))
  })
  
  # clear the chosen category on back button press
  observeEvent(input$clear, selections(NULL))
}

shinyApp(ui, server)

You need to use a technique similar to what is described here (essentially map the y-axis clicked value back to the data)

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.