如何让R语言plotly地图悬停文本仅显示国家名称
解决Plotly地图弹窗仅显示国家名称的问题
你当前的代码中,Plotly默认会在弹窗里自动附加z列的数字值、locations对应的ISO代码,即便设置了text = ~mapname也无法覆盖这些默认显示项。要实现仅显示国家名称,只需通过两个参数精确控制弹窗内容:
修改后的完整代码
# Plotly 地图 library(plotly) library(dplyr) # 加载dplyr以使用rename函数 countrylabeldata <- iso3166 countrylabeldata <- rename(countrylabeldata, "iso-a3" = a3) Swahili_countries <- c("BDI","OMN", "RWA","SSD", "SOM", "MDG", "ZMB") Official_Swahili_countries <- c("TZA", "UGA", "KEN", "COD") countrylabeldata$include <- ifelse(countrylabeldata$`iso-a3` %in% Swahili_countries, 1, 0) countrylabeldata$include <- ifelse(countrylabeldata$`iso-a3` %in% Official_Swahili_countries, 2, countrylabeldata$include) ncols <- 3 zseq <- seq(0,1,length.out=ncols+1) cols <- c("lightgrey", "red","purple") colorScale <- data.frame( z = c(0,rep(zseq[-c(1,length(zseq))],each=2),1), col=rep(cols,each=2) ) colorScale$col <- as.character(colorScale$col) g <- list( showframe = FALSE, showcoastlines = FALSE, projection = list(type = 'orthographic') ) fig <- plot_geo(countrylabeldata) %>% add_trace( z = ~include, color = ~include, colorscale=colorScale, text = ~mapname, locations = ~`iso-a3`, hoverinfo = 'text', # 关键:指定弹窗仅显示text内容 texttemplate = '%{text}', # 明确弹窗显示模板为国家名称 colorbar=list(tickmode='array', title="Level of Swahili Spoken", tickvals=c(.3,1.0,1.7), ticktext=c("Not Widely Spoken","Spoken","Official Language"), ticklen=.1) ) %>% layout( title = 'Swahili Speaking Countries', geo = g, margin = list(l = 20, r = 20, b = 20, t = 50), annotations = list(x = 1.4, y = .2, text = 'Source:CIA World Factbook', xref='paper', yref='paper', showarrow = F, xanchor='right', yanchor='auto', xshift=0, yshift=0, font = list(size = 10)) ) %>% colorbar(title = "Swahili", x = 1, y = 0.75) fig
关键改动说明
hoverinfo = 'text':强制Plotly弹窗只展示text参数指定的内容,屏蔽默认附加的z值、ISO代码等信息。texttemplate = '%{text}':进一步明确弹窗的显示模板,确保完全仅渲染国家名称,避免任何额外内容。- 补充加载
dplyr包:原代码中的rename函数依赖该包,不加载会导致报错。
内容的提问来源于stack exchange,提问作者user20934000
相关产品推荐
相关产品推荐

