Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

r - Hyperlinking text in a ggplot2 visualization

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...