Search code examples
rggplot2plotlyhoverggplotly

Modify hovertext in ggplotly


I'm creating a choropleth using simple features and ggplot, turning it into plotly output using the ggplotly function, then trying to update the hovertext info as shown below. I have no problem doing this on scatter plots, but no matter what I change with the choropleth, I seem to get the default hovertext.

There is no error messages, and I also tried experimenting with hovertemplate and continued to get the same result.

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

df <- spData::us_states

g <- ggplot() +
  geom_sf(data = df, aes(fill = total_pop_15)) +
  theme_minimal() +
  theme(axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        panel.grid.major = element_blank()) +
  scale_fill_continuous(name = "Total Pop 15", labels = comma) 

fig <- ggplotly(g) %>%
  style(hovertext = paste("State:", df$NAME,
                          "<br>Pop:", df$total_pop_15),
        hoveron = "fills")
fig

Solution

  • You need to set your hoverinfo/text within your geom. And also set the tooltip to "text" in ggplotly.

    library(tidyverse)
    library(sf)
    library(plotly)
    library(scales)
    
    df <- spData::us_states
    
    g <- ggplot() +
      geom_sf(data = df, aes(fill = total_pop_15,
                             text = sprintf("State: %s<br>Pop: %s", NAME, total_pop_15))) +
      theme_minimal() +
      theme(axis.text.x = element_blank(),
            axis.text.y = element_blank(),
            panel.grid.major = element_blank()) +
      scale_fill_continuous(name = "Total Pop 15", labels = comma) 
    
    ggplotly(g, tooltip = "text")