将鼠标悬停在 R Plotly 地图中的多边形中心时,交互式图例不显示。仅出现在轮廓(形状)上

问题描述 投票:0回答:1

我正在使用 R 中的 Plotly 创建交互式地图(形状)。该地图显示不同部门的#frequencies。但是,将鼠标悬停在多边形中心时,不会显示包含部门信息的工具提示。仅当鼠标悬停在多边形边缘时才会出现工具提示。

我已经尝试在工具提示#configuration中使用图层和位置属性,但工具提示仍然没有一致地出现在多边形的中心#。

我将不胜感激任何建议或解决方案,使工具提示在悬停在地图上时出现在#多边形的中心。

maa = read_sf("map.shp")

map = map %>% mutate(across(c("Frecuency", "Im", "Fo", "April", "July"),
    ~ifelse(is.na(.), 0, .)))

g_map = map %>%
    ggplot(aes(fill = Frecuency, text = paste("Dp: ", NAME, "",
    "Frecuency: ", Frecuency, "","I: ", Im, "
    ",
    "F: ", Fo, "
    ",
    "Abril: ", April, "
    ",
    "Julio: ", July))) +
    geom_sf() +
    scale_fill_gradient(low = "white", high = "darkblue") +
    labs(fill = "Scale", title = "Title") +
    theme_minimal() +
    theme_void()+
    theme(axis.line = element_blank())

# Convert to plotly
g_mapa_int = ggplotly(g_map, tooltip = "text")%>%
    config(displayModeBar = FALSE) %>%
    config(showLink = FALSE)

# Print
g_mapa_int

我将不胜感激任何建议或解决方案,使工具提示在悬停在地图上时出现在多边形的中心。

r ggplot2 plotly shapes ggplotly
1个回答
0
投票

您的问题无法重现。所以我使用了

sf
包中北卡罗来纳州的数据。

使用 UDF 构建绘图后,您可以更改

hoveron
参数。

以下是使用 NC 数据的示例。我检查每条轨迹并更改

hoveron
参数。如果同一县捕获了多个工具提示,我只使用第一个。

library(tidyverse)
library(plotly)
library(sf)

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

# built to somewhat replicate the conditions of the plot in your question
g <- ggplot(nc, aes(fill = AREA, text = paste0("Name: ", NAME, "Area: ", AREA))) +
  geom_sf() + scale_fill_gradient(low = "white", high = "darkblue") +
  labs(fill = "Scale", title = "Title") +
  theme_void()

fixer <- function(gp) {
  lapply(1:length(gp$x$data), \(m) {
    gp$x$data[[m]]$hoveron <<- "fills"               # hover on the fill, not line
    if(length(gp$x$data[[m]]$text > 1)) {
      gp$x$data[[m]]$text <<- gp$x$data[[m]]$text[1] # only one tooltip per county
    }
  })
  gp
}

ggplotly(g, tooltip = "text") %>% fixer() # call the UDF to change tooltips
© www.soinside.com 2019 - 2024. All rights reserved.