Hyperlinking text in a ggplot2 visualization

Here is one option that I used.

Your example:

library(tidyverse)
library(xml2)
df <- mtcars %>%
  rownames_to_column('car') %>%
  slice(5:8) %>%
  mutate(
    link = c(
      'https://de.wikipedia.org/wiki/AMC_Hornet', 
      'https://en.wikipedia.org/wiki/Plymouth_Valiant',
      'https://en.wikipedia.org/wiki/Plymouth_Duster',
      'https://en.wikipedia.org/wiki/Mercedes-Benz_W123'
    )
  ) 
p <- df %>%
  ggplot(aes(x = mpg, y = car)) +
  geom_point(size = 2) 

And then:

ggsave( tf1 <- tempfile(fileext = ".svg"), p)
links <- with(df, setNames(link, car))

xml <- read_xml(tf1)
xml %>%
  xml_find_all(xpath="//d1:text") %>% 
  keep(xml_text(.) %in% names(links)) %>% 
  xml_add_parent("a", "xlink:href" = links[xml_text(.)], target = "_blank")
write_xml(xml, tf2 <- tempfile(fileext = ".svg"))

If you open tf2 in your browser:

enter image description here

You can then covert this to a pdf (taken from @captcoma's comment below):

library(rsvg)
rsvg_pdf(tf2, "out.pdf")

@user20650 Here is a 'gridSVG' solution:

library(tidyverse)

links <- c('https://en.wikipedia.org/wiki/Plymouth_Duster',
           'https://de.wikipedia.org/wiki/AMC_Hornet', 
           'https://en.wikipedia.org/wiki/Mercedes-Benz_W123',
           'https://en.wikipedia.org/wiki/Plymouth_Valiant')

mtcars %>%
    rownames_to_column('car') %>%
    slice(5:8) %>%
    mutate(
        link = links
    ) %>%
    ggplot(aes(x = mpg, y = car)) +
        geom_point(size = 2)


library(grid)
## Force 'grid' grobs from 'ggplot2' plot
grid.force()
## List all grobs in plot
grid.ls()
## Find the grobs representing the text labels on the axes
tickLabels <- grid.grep("axis::text", grep=TRUE, global=TRUE)
## Check which one is the y-axis
lapply(tickLabels, function(x) grid.get(x)$label)

## Add hyperlinks to the axis tick labels
library(gridSVG)
grid.hyperlink(tickLabels[[1]],
               href=links,
               group=FALSE)
## Export to SVG (and view in a browser)
grid.export("linked-plot.svg")

enter image description here

Tags:

R

Ggplot2