How to furnish a ggplot2 figure with a hyperlink?

2019-04-07 14:05发布

I am trying to furnish a ggplot2 plot with a hyperlink:

This works:

library(gridSVG)
library(lattice)

xyplot(mpg~wt, data=mtcars, main = "Link to R-project home")
mainGrobName <- grep("main", grid.ls()[[1]], value=TRUE)
grid.hyperlink(mainGrobName, "http://www.r-project.org")
gridToSVG("HyperlinkExample.svg")

This not:

p = ggplot(mtcars, aes(wt, mpg)) + geom_point()+ labs(title="link")
print(p)
mainGrobName <- grep("title", grid.ls()[[1]], value=TRUE)
grid.hyperlink(mainGrobName, "http://www.r-project.org")
gridToSVG("HyperlinkExample.svg")

Any hints on this?

标签: r svg ggplot2
2条回答
Fickle 薄情
2楼-- · 2019-04-07 14:24

As far as getting the correct mainGrobName this code would succeed (and not create the distracting side-effects by setting print=FALSE):

grep("title", grid.ls(print=FALSE)$name, value=TRUE)
#[1] "title.2-4-2-4"

The structure of the plot object is clearly more complex than in the lattice situation and the gridToSVG does not capture it by default:

grep("title", grid.ls()$name, value=TRUE)
#--------------------
GRID.gTableParent.125
  background.1-5-6-1
  spacer.4-3-4-3
  panel.3-4-3-4
    grill.gTree.103
      panel.background.rect.94
      panel.grid.minor.y.polyline.96
      panel.grid.minor.x.polyline.98
      panel.grid.major.y.polyline.100
      panel.grid.major.x.polyline.102
    geom_point.points.90
    panel.border.zeroGrob.91
  axis-l.3-3-3-3
    axis.line.y.zeroGrob.113
    axis
  axis-b.4-4-4-4
    axis.line.x.zeroGrob.107
    axis
  xlab.5-4-5-4
  ylab.3-2-3-2
  title.2-4-2-4

This is also interesting output but I fail to see how I can get gridToSVG to convert it into a useful HTML object:

grid.ls( print=pathListing )$name
查看更多
祖国的老花朵
3楼-- · 2019-04-07 14:38

I have asked Simon Potter, one of the authors of the gridSVG package: Here is his (working) answer:

I suggest you try the development version here:

http://r-forge.r-project.org/R/?group_id=1025

It contains a workaround specifically to deal with gTables (and therefore ggplot2 graphics).

So to try and get your example to work, start up a new R session and run the following code:

install.packages("gridSVG", repos="http://R-Forge.R-project.org")
library(gridSVG)
library(ggplot2)
(p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + labs(title="link"))
titleGrobName <- grep("title", grid.ls(print=FALSE)$name, value=TRUE)
grid.hyperlink(titleGrobName, "http://www.r-project.org/")
gridToSVG("HyperlinkExample.svg", "none", "none")

The only real difference here are the additional parameters given to gridToSVG(). This is mainly to reduce the output to just the SVG file and an HTML wrapper (otherwise you also get some JSON data, which is not useful for your example).

查看更多
登录 后发表回答