我有两个数据集df_state和df_city。
df_state的总和是一个数值(net_value_x)。
df_city在城市级别细分了数值(value_x)
这只是德克萨斯州的一个示例:
df_state:
state_abb, net_value_x
.
.
TX 18.94
.
.
df_city:
state_abb, city, value_x
.
.
TX Dallas 14
TX Houston 2
TX Austin 2.94
.
.
这是我使用
hcmap
中的highcharter
函数在状态级别绘制的代码。hcmap("countries/us/us-all", data = df_state, value = "net_value_x",
joinBy = c("hc-a2", "code"), name = "net_value_x",
dataLabels = list(enabled = TRUE, format = "{point.name}"),
borderColor = "#FAFAFA", borderWidth = 0.1,
tooltip = list(valueDecimals = 2))
这是我得到的地图。悬停在德克萨斯州的样本数据。
我需要的是进一步深入到城市层面。我将来也可能会得到县级数据。
我正在链接中看到这样的内容:
highchart drilldown
最佳答案
尽管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)
关于r - 使用HighCharter从各州细化美国城市/县 map ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48898192/