DJC
DJC

Reputation: 1601

Store plotly tooltip information outside of ggplot object

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")

Upvotes: 2

Views: 47

Answers (1)

Aur&#232;le
Aur&#232;le

Reputation: 12819

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")

Upvotes: 2

Related Questions