wilkox / treemapify

🌳 Draw treemaps in ggplot2
http://wilkox.org/treemapify
213 stars 18 forks source link

drill down treemap in shiny? #22

Closed dockstreet closed 6 years ago

dockstreet commented 6 years ago

Is there a way to drill down into subgroups with treemaply in shiny ? perhaps by clicking on a tooltip with an html link to observe or tile to expand?

Would this approach work? https://stackoverflow.com/questions/45021775/use-on-click-for-a-treemapify-object-in-r-shiny

I've seen treemap, on the pokemon dashboard which does support a drilldown http://jkunst.com/flexdashboard-highcharter-examples/pokemon/

hoping that treemapify would have similar behavior or could be achieved with a click to post back to shiny

wilkox commented 6 years ago

I'm not a Shiny expert but here's an approach that seems to work:

library(ggplot2)
library(shiny)
library(tidyverse)
library(treemapify)

ui <- shinyUI(fluidPage(
  titlePanel("Drill-down treemap"),
  mainPanel(
    plotOutput("graph", width = "100%", click = "tclick"),
    actionButton("zoomout", "Zoom out")
  )
))

server <- shinyServer(function(input, output, session) {

  data <- G20
  makeReactiveBinding('data')

  output$graph <- renderPlot({
    ggplot(data, aes(area = gdp_mil_usd, fill = hdi, subgroup = region, label = country)) +
      geom_treemap() +
      geom_treemap_text(reflow = T) +
      geom_treemap_subgroup_text(grow = T, alpha = 0.5) +
      geom_treemap_subgroup_border()
  })  

  # When the 'Zoom out' button is clicked, reset the treemap
  observeEvent(input$zoomout, {
    data <<-
  })

  # When a subgroup is clicked
  observeEvent(input$tclick, {

    # Calculate coordinates of main treemap
    coords <- treemapify(data, area = "gdp_mil_usd", fill = "hdi", label =
                         "country", group = "region",  xlim = c(0, 1), ylim =
                         c(0, 1))

    # Figure out which tile was clicked and what subgroup it belongs to
    clickedSubgroup <- coords %>%
      filter(xmin < input$tclick$x) %>%
      filter(xmax > input$tclick$x) %>%
      filter(ymin < input$tclick$y) %>%
      filter(ymax > input$tclick$y) %>%
      .$group

    # Subset data to only that subgroup
    data <<- data %>% filter(region == clickedSubgroup)
  })
})
shinyApp(ui=ui,server=server)