Гиперссылка текста в виде ggplot2
В настоящее время, если я хочу показывать данные в таблице в R, я могу гиперссылки текста через markdown, html href или LaTeX href. Это часто бывает полезно для получения доступа к дополнительной информации о конкретном элементе без загромождения таблицы.
Как можно передавать те же типы гиперссылок в визуализации, сделанные с помощью ggplot2?
Так, например, если я сделаю этот сюжет:
![введите описание изображения здесь]()
С помощью приведенного ниже кода, как я могу сделать гиперссылку текста оси на соответствующие страницы википедии?
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)
Ответы
Ответ 1
Вот один из вариантов, который я использовал.
Ваш пример:
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
в своем браузере:
![введите описание изображения здесь]()
Ответ 2
@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]()