我正在尝试使用likert包和gridSVG包的组合在Likert数据的图中嵌入超链接。我想将每个问题的文本链接到一个单独的链接,但我遇到了问题。下面的代码在每个问题的文本中都嵌入了一个链接,但是我无法弄清楚如何单独嵌入每个问题,因为这组问题似乎被整合在一起。提前感谢您的意见。
#creates an example plot from sample data from likert package.
require(likert)
data(pisaitems)
items29 <- pisaitems[,substr(names(pisaitems), 1,5) == "ST25Q" ]
names(items29) <- c("Magazines", "Comic books", "Fiction",
"Non-fiction books", "Newspapers")
l29 <- likert(items29)
summary(l29)
plot(l29)
require(grid)
require(gridSVG)
#identifies grob of question text (all questions are in a single grob)
titleGrobName <- grep("axis-l.3-3-3-3", grid.ls(print=FALSE)$name, value=TRUE)
#embeds link in grob
grid.hyperlink(titleGrobName, "http://www.r-project.org")
#creates svg
gridToSVG("testPlot.svg", "none", "none")
答案 0 :(得分:2)
这种分组GROB
并不罕见。由于我认为我们不想重写likert
来取消对这些内容进行取消组合,因此在使用SVG
grid
之后操纵XML
可能会更好。这是实现这一目标的一种方式。
如果您希望此图片成为更大网页的一部分,我们也可以在HTML/JavaScript
一侧添加链接。
#creates an example plot from sample data from likert package.
require(likert)
data(pisaitems)
items29 <- pisaitems[,substr(names(pisaitems), 1,5) == "ST25Q" ]
names(items29) <- c("Magazines", "Comic books", "Fiction",
"Non-fiction books", "Newspapers")
l29 <- likert(items29)
summary(l29)
plot(l29)
# if possible to use htmltools from RStudio
# install.packages("htmltools")
# then we can add the links on the
# XML side instead of in grid
library(XML)
library(htmltools)
library(gridSVG)
# export as XML SVG
likert_svg <- grid.export("", addClasses=TRUE)$svg
# find our axes
nodes <- getNodeSet(
likert_svg,
# thanks http://stackoverflow.com/questions/5818681/xpath-how-to-select-node-with-some-attribute-by-index
"(//x:g[contains(@id,'axis')])[1]//x:tspan",
"x"
)
lapply(
nodes,
function(node){
# get the text value of the node
lbl = xmlValue(node)
# remove the text from our node
xmlValue(node) <- ""
# create a <a href=> hyperlink
# https://www.w3.org/wiki/SVG_Links
a_node <- newXMLNode(
"a",
####### change your link here ###########
attrs = c("xlink:href"=paste0("http://google.com/search?q=",lbl)),
lbl
)
# add our new linked text to the node
addChildren(node, a_node)
}
)
# look at it in the browser/RStudio Viewer
browsable(
HTML(
saveXML(
# export as SVG XML
likert_svg,
prefix = ""
)
)
)