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

房东的猫 提交于 2019-12-30 05:27:17

问题


Is there a way to use a node as a link to an external website using the function forceNetwork() in the networkD3 package in r? I was thinking maybe modifying the clickAction?

Example data:

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)

Desired outcome: When a user clicks on a node, a new tab will open (e.g. window.open) pointing to the associated URL for the node - How can I get clickAction to point to MisNodes$URL[d.index]?


回答1:


networkD3 design does not make this easy. Here is one way to answer. I'll try to comment inline to explain what we are doing in each step.

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


来源:https://stackoverflow.com/questions/36895960/linking-a-node-in-networkd3-to-a-website-using-clickaction-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!