Interactive legend not showing when hovering in the center of polygons in an R Plotly map. Only appears over the outline (shape)

#I am creating an interactive map (shape) using Plotly in R. The map displays #frequencies in different departments. However, when hovering over the center #of the polygons, the tooltip with the department information does not appear. #The tooltip only appears when hovering over the edges of the polygons.

#I have tried using the layer and position properties in the tooltip #configuration, but the tooltip still doesn't appear consistently in the center #of the polygons.

#I would appreciate any suggestions or solutions to make the tooltip appear in #the center of the polygons when hovering over the map.
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

I have the same problem. Would be interested in a solution to this.

1 Like

Someone great gave me this solution on another forum. Copy the code below and when you print the graph you add the function.
library(tidyverse)
library(plotly)
library(sf)

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

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.