ggplotly地图hover问题:区域边界与内部显示相同自定义文本
解决ggplotly地图hover区域内部与边界显示相同自定义文本的问题
要实现hover地图区域内部和边界时都显示自定义文本,需要手动为fill层指定tooltip内容,同时设置hover触发范围。修改后的完整代码如下:
library(rnaturalearth) library(plotly) world <- ne_countries(returnclass = "sf") w <- world[world$iso_a2_eh != -99, c("geometry", "name", "iso_a2_eh", "subregion")] w$weur <- ifelse(w$subregion == "Western Europe", 1, 0) # 提前把自定义文本存为数据框列,方便后续赋值 w$text <- paste0("country: ", w$name, "\n country code: ", w$iso_a2_eh) # 生成ggplot对象并转换为ggplotly fig <- ggplotly( ggplot(data= w, aes(text = text)) + geom_sf(color= "white", aes(fill = as.character(weur)), linewidth = 0.2) + theme(legend.position="none", panel.background = element_rect(fill = "white"), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + coord_sf(xlim=c(-10,40), ylim=c(30,70), expand= FALSE, label_axes = "SW") + scale_fill_manual(values = c("gray", "lightgreen"), na.value="#dadada", drop=F), tooltip = "text" ) # 关键修改:设置hover触发范围,并为fill层传递自定义文本 fig <- fig %>% style(hoveron = "fills+lines") %>% # 遍历每个trace,将自定义text赋值给fill类型的trace lapply(function(trace) { if (trace$type == "scatter" && !is.null(trace$fill)) { trace$text <- w$text trace$tooltip <- "text" } trace }) %>% plotly_build() fig
核心逻辑说明:
hoveron = "fills+lines":明确指定hover触发范围包含填充区域和边界线条- ggplotly会将
geom_sf拆分为填充层和边界层两个独立trace,默认情况下填充层的tooltip不会继承我们定义的自定义文本,因此需要遍历trace对象,找到对应填充层的trace,手动将自定义文本赋值给它,并强制tooltip使用该文本内容,确保hover填充区域和边界时显示一致的内容。
内容的提问来源于stack exchange,提问作者Luigi
相关产品推荐
相关产品推荐

