networkD3的forceNetwork和htmlwidgets

时间:2017-12-01 10:52:11

标签: javascript r htmlwidgets networkd3

我搜索使用forceNetwork将工具提示附加到节点之间的链接(即边缘)的方法是空的。这些是我发现的最相关的例子:

那么如何向forceNetwork链接添加工具提示?可能吗?我看到forceNetwork有一个clickAction属性,你可以使用它来用htmlwidgets调用JS。不幸的是,clickAction似乎作用于节点,而不是它们之间的链接。

这是我可重复的例子:

library(networkD3)
library(htmlwidgets)

# Load data
data(MisLinks)
data(MisNodes)  

# Make network using sample data
fn <- forceNetwork(
  Links  = MisLinks, Nodes   = MisNodes,
  Source = "source", Target  = "target",
  Value  = "value",  NodeID  = "name",
  Group  = "group"
)

# Get the target variable in fn$x$links (an integer id) to show up as a tooltip when user hovers over a link (i.e. edge) in the graph
fnrender <- htmlwidgets::onRender(
  fn,
  '
  function(el, x) {
  d3.selectAll(".link").select("title")
  .text(function(d) { return d.target; });
  }
  '
)

# display the result
fnrender 

我的目标是让一个字符串变量描述当用户将鼠标悬停在它们之间的链接时显示的两个节点之间的关系。任何关于如何前进的建议都将非常感激。

1 个答案:

答案 0 :(得分:1)

你必须'追加'标题......

library(networkD3)
library(htmlwidgets)

# Load data
data(MisLinks)
data(MisNodes)

# Make network using sample data
fn <- forceNetwork(
  Links  = MisLinks, Nodes   = MisNodes,
  Source = "source", Target  = "target",
  Value  = "value",  NodeID  = "name",
  Group  = "group"
)

# Get the target variable in fn$x$links (an integer id) to show up as a tooltip when user hovers over a link (i.e. edge) in the graph
fnrender <- htmlwidgets::onRender(
  fn,
  '
  function(el, x) {
    d3.selectAll(".link").append("svg:title")
      .text(function(d) { return d.source.name + " -> " + d.target.name; })
  }
  '
)

# display the result
fnrender