What's the best way to drill down a plot

I want to update a plot based on click on the same plot.

Ex:

If I click a bar graph of country
Plot updates to states
And then to districts and city and so on...

What's the shiny way of creating such plot in fastest manner possible with plotly.

Here are some examples of drill-down using sales data https://plotly-r.com/linking-views-with-shiny.html#drill-down

Here's how you could modify that pie chart example into a bar chart that drills-down into geographic categories

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) {
      gapminder %>%
        group_by(continent) %>%
        summarise(pop = sum(as.numeric(pop))) %>%
        plot_ly() %>%
        add_bars(x = ~continent, y = ~pop)
    } else {
      gapminder %>%
        filter(continent %in% selections()) %>%
        group_by(country) %>%
        summarise(pop = sum(as.numeric(pop))) %>%
        plot_ly() %>%
        add_bars(x = ~country, y = ~pop)
    }
  })
  
  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)
1 Like

Thanks for such a solution that means

I need to keep the state of my plots or filters in a reactive values. And use only those part in observe event rather than calling the entire render argument in observe event.

Thanks again.

This topic was automatically closed 7 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.