Search code examples
rggplot2plotlyr-plotlyggplotly

How do I format the names of the variables in the R plotly tooltip?


I have been trying to make a map of the U.S. with a superimposed scatterplot of shootings with both the number of people killed and injured in the hoverinfo label of each point. However, the label pops up as "num_killed" and I would like to format this as "Number Killed: ". So far, I have tried labeling the variables in the ggplot section, to no avail. Is there any way to change how the variable name is printed in the tooltip?

Here is my code:

library(plotly)
library(dplyr)
library(ggplot2)

us <- map_data("state")
library(maps)

g <- ggplot() +
  geom_polygon(data = us, aes(x=long, y = lat, group = group), fill="grey", alpha=0.3) +
  geom_point(data=shootings, aes(x=lng, y=lat, size = num_killed, color = num_injured)) +
  labs(color = "Number Injured", size = "Number Killed", num_killed = "Number Killed", num_injured = "Number Injured")
plot <- ggplotly(g)

Here is the result: Image showing tooltip

Dataset attached is the processed csv of this database: http://www.gunviolencearchive.org/reports/mass-shooting?page=1 (processed as data frame).


Solution

  • This should give you what you want:

    g <- ggplot() +
      geom_polygon(data = us, aes(x=long, y = lat, group = group), fill="grey", alpha=0.3) +
      geom_point(data=shootings, aes(x=lng, y=lat, size = num_killed, color = num_injured,
                                     text = paste('lng: ', lng,
                                                  '<br>lat:', lat, 
                                                  '<br>Number Killed:', num_killed,
                                                  '<br>num_injured:', num_injured)))
    
    ggplotly(g, tooltip = "text")