虽然 highcharter 的向下钻取功能很有用,但当您在每个状态下都有数据时,它需要在渲染时为每个底层状态加载地图。我采取的一种方法基本上是在绘制州地图和县地图之间切换,如下所示。
## Library
library(shiny)
library(shinyjs)
library(dplyr)
library(highcharter)
library(stringr)
## Load maps at start for speed
maps <- sapply(
X = c("us-all", "us-tx-all"),
simplify = FALSE,
FUN = function(x) { highcharter::download_map_data(paste0("countries/us/", x)) }
)
ui <- shiny::fluidPage(
shinyjs::useShinyjs(),
highcharter::highchartOutput(outputId = "map"),
shiny::uiOutput(outputId = "ui")
)
server <- function(input, output, session) {
## USA map with just TX as example
state_map <- shiny::reactive({
highcharter::highchart() %>%
highcharter::hc_add_series_map(
map = maps[["us-all"]],
df = data.frame(state_abbr = c("TX"), y = c(10)),
joinBy = c("postal-code", "state_abbr"),
value = "y"
) %>%
highcharter::hc_plotOptions(
series = list(
allowPointSelect = TRUE,
events = list(
click = htmlwidgets::JS(
"function(event) {
Shiny.setInputValue(
'geo_click',
event.point.state_abbr,
{priority: 'event'}
);
}"
)
)
)
)
})
## County map
county_map <- shiny::reactive({
highcharter::highchart() %>%
highcharter::hc_add_series_map(
map = maps[[paste0("us-", stringr::str_to_lower(input$geo_click), "-all")]],
df = data.frame(city = c("Gray", "Leon", "Lamb", "Duval"), y = c(1, 4, 2, 3)),
joinBy = c("name", "city"),
value = "y"
)
})
## Set to state map at outset
output$map <- highcharter::renderHighchart({ state_map() })
## If state clicked, add button to go back to state map
output$ui <- shiny::renderUI({
if (!is.null(input$geo_click)) {
shiny::actionButton(
inputId = "geo_button",
label = "Return to USA Map"
)
}
})
## If button clicked, reset input, hide button, and go back to state map
shiny::observeEvent(
eventExpr = input$geo_button,
handlerExpr = {
output$map <- highcharter::renderHighchart({ state_map() })
shinyjs::hide(id = "geo_button")
}
)
## If state clicked, go to county map and show button
shiny::observeEvent(
eventExpr = input$geo_click,
handlerExpr = {
output$map <- highcharter::renderHighchart({ county_map() })
shinyjs::show(id = "geo_button")
}
)
}
shiny::shinyApp(ui = ui, server = server)