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:
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)
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:
You can then covert this to a pdf (taken from @captcoma's comment below):
library(rsvg) rsvg_pdf(tf2, "out.pdf")
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