R使用highcharter绘制地图时tooltip无法读取dataframe数值问题
R语言highcharter地图tooltip读取业务数据表字段解决方案
问题原因
你在hc_add_series_map中通过value参数指定的数值字段,会被Highcharts默认映射为点对象的value属性,不会保留原字段名occurences挂载到this.point下,因此直接读取this.point.occurences会返回空值。
解决方案
只需要修改hc_tooltip中JS格式化函数的取值字段,把this.point.occurences替换为this.point.value即可,同时修正你代码中hc_tooltip结尾的管道符笔误(缺了>)。
修改后完整可运行代码如下:
library(httr) library(highcharter) library(scales) map <- "https://code.highcharts.com/mapdata/custom/world-highres.geo.json" %>% GET() %>% content() %>% jsonlite::fromJSON(simplifyVector = FALSE) sample_table <- data.frame(name = c("Spain","France","China"), continent = c("Europe","Europe","Asia"), occurences = c(150,70,120)) cols3 <- scales::viridis_pal(option = "turbo", begin = 0.4, direction = 1)(length(unique(sample_table$name))) highchart(type = "map") %>% hc_title(text = "Map Title") %>% hc_subtitle(text = "Map Subtitle") %>% hc_add_series_map(map = map, df = sample_table, joinBy = "name", value = "occurences", dataLabels = list(enabled = TRUE ,format = "{point.properties.hc-a2}") ) %>% hc_colors(cols3) %>% hc_colorAxis(stops = color_stops(colors = cols3)) %>% hc_tooltip( useHTML = TRUE, formatter = JS( " function(){ outHTML = '<b>' + this.point.name + '</b> <br>' + this.point.continent + '</b> <br>' + this.point.value return(outHTML) } " )) %>% hc_mapNavigation(enabled = TRUE)
修改后tooltip可正常显示数值,效果参考:
拓展:如需保留原字段名访问
如果需要在JS中直接通过this.point.occurences访问数值,可在hc_add_series_map中添加keys参数显式声明要保留的字段:
hc_add_series_map(map = map, df = sample_table, joinBy = "name", value = "occurences", keys = c("name", "continent", "occurences"), dataLabels = list(enabled = TRUE,format = "{point.properties.hc-a2}") )
这种场景下不需要修改formatter的原有取值逻辑,也能正常读取occurences字段。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

