使用 clickAction = NULL 将 networkD3 中的节点链接到网站

linking a node in networkD3 to a website using clickAction = NULL

有没有办法使用 rnetworkD3 包中的函数 forceNetwork() 将节点用作 link 到外部网站?我在想也许可以修改 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