R Plotly地图多边形中心hover无提示框,仅边缘显示问题求助
解决方案
1. 改用Plotly原生SF支持(推荐)
直接用Plotly处理SF对象,跳过ggplot转换环节,能更精准控制多边形的hover交互范围,确保整个区域都能触发提示框:
library(plotly) library(sf) library(dplyr) # 读取并预处理数据 map_sf = read_sf("map.shp") %>% mutate(across(c("Frecuency", "Im", "Fo", "April", "July"), ~ifelse(is.na(.), 0, .))) # 构建交互式地图 g_mapa_int = plot_ly(map_sf) %>% add_sf( fill = ~Frecuency, text = ~paste("Dp: ", NAME, "<br>", "Frecuency: ", Frecuency, "<br>", "I: ", Im, "<br>", "F: ", Fo, "<br>", "Abril: ", April, "<br>", "Julio: ", July), hoverinfo = "text", colors = colorRamp(c("white", "darkblue")) ) %>% layout( title = "Title", legend = list(title = list(text = "Scale")) ) %>% config(displayModeBar = FALSE, showLink = FALSE) # 显示地图 g_mapa_int
2. 为多边形添加不可见中心点标记
计算每个多边形的质心,添加透明/零尺寸的点标记,让中心区域也能触发提示框:
library(ggplot2) library(plotly) library(sf) library(dplyr) map = read_sf("map.shp") %>% mutate(across(c("Frecuency", "Im", "Fo", "April", "July"), ~ifelse(is.na(.), 0, .))) %>% # 计算质心坐标 mutate(centroid = st_centroid(geometry)) %>% st_coordinates(centroid) %>% as.data.frame() %>% rename(lon = X, lat = Y) %>% bind_cols(map, .) g_map = map %>% ggplot(aes(fill = Frecuency)) + geom_sf(aes(text = paste("Dp: ", NAME, "<br>", "Frecuency: ", Frecuency, "<br>", "I: ", Im, "<br>", "F: ", Fo, "<br>", "Abril: ", April, "<br>", "Julio: ", July))) + # 添加不可见的质心点 geom_point(aes(x = lon, y = lat, text = text), size = 0, alpha = 0) + scale_fill_gradient(low = "white", high = "darkblue") + labs(fill = "Scale", title = "Title") + theme_void() g_mapa_int = ggplotly(g_map, tooltip = "text") %>% config(displayModeBar = FALSE, showLink = FALSE) g_mapa_int
3. 修改ggplotly生成的Trace交互属性
如果坚持使用ggplot转换,可手动调整Plotly Trace的hoveron参数,让填充区域也能触发提示:
g_mapa_int = ggplotly(g_map, tooltip = "text") %>% config(displayModeBar = FALSE, showLink = FALSE) %>% # 设置hover触发范围为填充区域+线条 style(hoveron = "fills+lines", traces = 1) g_mapa_int
注:原代码存在变量名不一致问题(读取SF对象到maa但后续用map),需确保变量名统一。
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

