Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperlinking text in a ggplot2 visualization

Tags:

r

ggplot2

Currently if I want to show data in a table in R I can hyperlink text via markdown, html href, or LaTeX href. This is often nice for giving access to more info about a particular element w/o cluttering the table.

How is it possible to give the same kinds of hyperlinked text in a visualization made with ggplot2?

So for example if I make this plot:

enter image description here

With the code below, how can I make the axis text hyperlink to the wikipedia pages that correspond?

library(tidyverse)  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'         )     ) %>%     ggplot(aes(x = mpg, y = car)) +         geom_point(size = 2) 
like image 472
Tyler Rinker Avatar asked Feb 15 '17 20:02

Tyler Rinker


1 Answers

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") 
like image 176
lukeA Avatar answered Sep 20 '22 18:09

lukeA