ggplot2可视化中的超链接文本

时间:2017-02-15 20:52:25

标签: r ggplot2

目前,如果我想在R中的表中显示数据,我可以通过markdown,html href或LaTeX href超链接文本。这通常很适合访问有关特定元素的更多信息,而不会使表格混乱。

如何在使用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 个答案:

答案 0 :(得分:40)

这是我使用的一个选项。

你的例子:

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

答案 1 :(得分:4)

@ user20650这是一个'gridSVG'解决方案:

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