I would like to print an interactive ggplot graph using plotly. I use the plotly "tooltip" argument. I would like to use a variable argument to define the text argument of the aesthetic in ggplot.
This is the code :
library(tidyverse)
library(plotly)
df <- data.frame(ID = paste0("ID_",LETTERS[1:20]),
A = rnorm(20),
B = rnorm(20),
C = rnorm(20),
D = rnorm(20),
E = rnorm(20)
)
variable_to_tooltip <- c("C", "D")
graph <- df %>%
ggplot(aes(x=A, y = B,
text = paste("ID", ID,
"<br>C", C,
"<br>D", D)))+
geom_point()
ggplotly(graph, tooltip = "text")
The graph is OK, but I would like to use the "variable_to_tooltip" to define the text argument as the graph will be include in a loop and it will vary.
I did try to use the get() and !!sym() functions but didn't really understand how sym() was working nor if it could be useful to solve this problem.
Thanks a lot if someone can help ! Florent
One option would be to use tidyr::unite to create your tooltip and to add it as a column to your dataframe outside of ggplot:
library(tidyverse)
library(plotly)
set.seed(123)
df <- data.frame(
ID = paste0("ID_", LETTERS[1:20]),
A = rnorm(20),
B = rnorm(20),
C = rnorm(20),
D = rnorm(20),
E = rnorm(20)
)
variable_to_tooltip <- c("C", "D")
df <- df |>
unite(col = tooltip, all_of(c("ID", variable_to_tooltip)), sep = "<br>")
graph <- df %>%
ggplot(aes(
x = A, y = B,
text = tooltip
)) +
geom_point()
ggplotly(graph, tooltip = "text")

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With