Search code examples
rggplot2plotlyshapesggplotly

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


Solution

  • Your question isn't reproducible. So I used the data for North Carolina from the sf package.

    You can change the hoveron parameter after you build the plot with a UDF.

    Here's an example of what works with NC data. I go through each trace and change the hoveron parameter. If more than one tooltip was captured for the same county, I only use the first one.

    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