2017-02-15 20 views
10

当前,如果我想在R表中显示数据,我可以通过markdown,html href或LaTeX href超链接文本。这对于访问有关特定元素的更多信息(不会使表格混乱)通常很不错。在ggplot2可视化中超链接文本

在ggplot2制作的可视化文件中,如何提供相同类型的超链接文本?

因此,举例来说,如果我有这样的情节:

enter image description here

与下面的代码,我怎样才能使轴文本超链接到对应的维基百科页面?

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) 
+2

什么设备保存?很明显,JPEG等已经出来,但PDF可能可以通过网格。对于网页,可以通过D3.js/SVG画布进行,也许可以使用'ggplotly'进行初始转换。不过,我认为任何选择都不会很简单。 – alistaire

+0

我认为很难将单独的链接应用到轴文本,因为它们(*我认为*)只是一个grob,而不是单独的,但'gridSVG'包显示了在浏览器中查看时添加到grobs的链接的方法。所以你可以使用单独的grobs来获取点数,标签等,并添加链接到这些(我已经与这[这里](http://chat.stackoverflow.com/rooms/135813/gridsvg)) – user20650

+0

@alistaire我' d喜欢在knitr/rmarkdown内使用它pdf_document –

回答

11

这是我使用的一个选项。

你举的例子:

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) 

然后:

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

如果你在浏览器中打开tf2

enter image description here

+2

哇,这是令人印象深刻的! – Gregor

+0

我发现它很有用,但是,我不知道它是否适用于所有浏览器。我在Windows上使用Chrome 56和Firefox 50.1尝试了这个... – lukeA

+2

这太棒了。适用于MacOS上的Firefox,Safari,Chrome,Opera和Vivaldi。 – alistaire