有没有办法使用 r
中networkD3
包中的函数forceNetwork()
将节点用作指向外部网站的链接?我在想也许修改clickAction
?
示例数据:
library(networkD3)
data(MisLinks)
data(MisNodes)
# Create a random URL in the nodes dataset
MisNodes$URL <- paste0("http://www.RANDOMLINK_", sample(1:100, NROW(MisNodes)), ".com")
head(MisNodes)
MyClickScript <- 'alert(d.index)'
forceNetwork(Links = MisLinks, Nodes = MisNodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
Group = "group", opacity = 0.8,
clickAction = MyClickScript)
期望的结果:当用户单击节点时,将打开一个新选项卡(例如 window.open
) 指向节点的关联 URL - 如何让clickAction
指向MisNodes$URL[d.index]
?
networkD3
设计并不容易。 这里有一种方法可以回答。 我将尝试内联评论以解释我们在每一步中正在做什么。
library(networkD3)
# example from ?forceNetwork
data(MisLinks)
data(MisNodes)
# Create graph
fn <- forceNetwork(
Links = MisLinks, Nodes = MisNodes, Source = "source",
Target = "target", Value = "value", NodeID = "name",
Group = "group", opacity = 0.4, zoom = TRUE
)
# let's look at our forceNetwork
# nodes are provided to JavaScript
# in a nodes data.frame
str(fn$x$nodes)
# make up some links to demonstrate
# how we can add them to our nodes df
fn$x$nodes$hyperlink <- paste0(
'http://en.wikipedia.org/wiki/Special:Search?search=',
MisNodes$name
)
# then with our hyperlinks in our data
# we can define a click action to open
# the hyperlink for each node in a new window
fn$x$options$clickAction = 'window.open(d.hyperlink)'
fn