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)