Store plotly tooltip information outside of ggplot object

Viewed 34

Is it possible to store plotly tooltip information outside of a ggplot object? For example, I would like to go from this:

library(tidyverse)
library(plotly)

p1 <- mtcars %>% 
  ggplot(aes(x = mpg, y = hp, text = paste0("<b>MPG: </b>", mpg, "<br>",
                                            "<b>HP: </b>", hp))) +
  geom_point()

ggplotly(p1, tooltip = "text")

To this:

tooltip_text <- paste0("<b>MPG: </b>", mpg, "<br>",
                       "<b>HP: </b>", hp)

p1 <- mtcars %>% 
  ggplot(aes(x = mpg, y = hp, text = tooltip_text)) +
  geom_point()

ggplotly(p1, tooltip = "text")
1 Answers

Using quote and the bang-bang operator !! to unquote:

tooltip_text <- quote(paste0("<b>MPG: </b>", mpg, "<br>",
                         "<b>HP: </b>", hp))

p1 <- mtcars %>% 
  ggplot(aes(x = mpg, y = hp, text = !! tooltip_text)) +
  geom_point()

ggplotly(p1, tooltip = "text")
Related