rggiraph

ggiraph: tooltip with hyperlink?


I am trying to create an interactive scatterplot with ggiraph where the tooltip allows me to navigate to a webaddress (which pertains to the specific selected dot). Any idea whether this is actually possible and how to go about it? Many thanks for any advice!

library(tidyverse)
library(ggiraph)

my_df <- data.frame(stringsAsFactors=FALSE,
            x = c(0.5, 0.1),
            y = c(0.2, 0.9),
         link = c("bbcnews.com", "nyt.com"),
   link_name = c("bbc news", "nytimes")
)


my_plot <- my_df %>% 
  ggplot()+
  geom_point_interactive(aes(x=x,
                             y=y,
                             tooltip=paste0(link_name, 
                                            "\n",
                                            link)))
my_plot
girafe(ggobj=my_plot,
       height_svg = 5,
       width_svg = 5)

enter image description here


Solution

  • You can provide links through either the tooltip (written as html) or the onclick aesthetics. Personally, I prefer to use the onclick since the tooltip almost always disappears when you move the mouse cursor to click on a link.

    In the code below I've tried to add both, so you can try to click on the point itself or see if you are fast enough to click the link in the tooltip.

    library(tidyverse)
    library(ggiraph)
    
    my_df <- data.frame(stringsAsFactors=FALSE,
                x = c(0.5, 0.1),
                y = c(0.2, 0.9),
             link = c("http://bbcnews.com", "http://nyt.com"),
       link_name = c("bbc news", "nytimes")
    )
    
    my_plot <- my_df %>% 
      ggplot()+
      geom_point_interactive(aes(x=x,
                                 y=y,
                                 tooltip=paste0("<a href='", link, "'>",link_name, 
                                                "</a>\n",
                                                link), 
    onclick=paste0('window.open("', link , '")')))
    
    girafe(ggobj=my_plot,
           height_svg = 5,
           width_svg = 5)