-1

Is there any way, using , to display edge weights on the graph produced by networkD3::forceNetwork?

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
  • 1
    Welcome to SO and R. To help us help you please put your code and data in the question. You may find it helpful to write an excellent question by following the guidance in this link [MRE]. Please, please add some data in a dataframe format e.g. df <- data.frame(a = c(1, 2, 3), b = c("a", "b", "c")) obviously with your own data! And either explain what you have tried out prior to asking your question, ideally with the code you have tried. Thank you. – Peter Apr 25 '20 at 09:58

1 Answers1

2

The Value argument of networkD3::forceNetwork is a string that sets the name of the variable/column in the Links data frame which contains the value for each link. That value is typically the edge/link weight. The value in the specified variable for each link will determine the width of each link, showing the edge weight (if that's what the value refers to).

library(networkD3)
library(tibble)

nodes <- 
  tribble(
    ~name, ~group,
    "a",    1,
    "b",    1,
    "c",    1,
    "d",    1
  )

links <- 
  tribble(
    ~source, ~target, ~value,
    0,       1,       1,
    0,       2,       1,
    0,       3,       1,
  )

forceNetwork(Links = links, Nodes = nodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             Group = "group", opacity = 1)

enter image description here

links <- 
  tribble(
    ~source, ~target, ~value,
    0,       1,       1,
    0,       2,       20,
    0,       3,       100,
  )

forceNetwork(Links = links, Nodes = nodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             Group = "group", opacity = 1)

enter image description here


UPDATE 2020.04.26

Here's a way to add a text label to the links so that the value of the link weight will display when you hover the mouse over a link.

library(tibble)
library(networkD3)
library(htmlwidgets)

nodes <- 
  tribble(
    ~name, ~group,
    "a",    1,
    "b",    1,
    "c",    1,
    "d",    1
  )

links <- 
  tribble(
    ~source, ~target, ~value,
    0,       1,       1,
    0,       2,       20,
    0,       3,       100,
  )

fn <- forceNetwork(Links = links, Nodes = nodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             Group = "group", opacity = 1)

link_value_js <- '
  function(el) { 
    d3.select(el)
      .selectAll(".link")
      .append("title")
      .text(d => d.value);
  }
'

onRender(fn, link_value_js)

enter image description here

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56