1

I added the node label with its name and value to a network D3 Sankey in R using a javascript as follows:

javascript_string <- 
  'function(el, x){
    d3.select(el).selectAll(".node text")
      .text(d => d.name + " (" + d.value + ")");
  }'

The resulting Sankey shows some of these values upto 10 decimal places which is too precise. I only want for it to show the values upto 2 decimal places. What do I change in this javascript string to limit the d.value to 2 decimal places?

Thank you!

I tried adding node label with name and value to a network D3 sankey in R using a javascript string. It did add the labels as I wanted but some of the values in the resulting image were too precise. I want to limit it to 2 decimal places only.

Phil
  • 7,287
  • 3
  • 36
  • 66

1 Answers1

0

You can use D3 format function to apply numerous different formats to a number. See https://github.com/d3/d3-format

For example, here I round to zero decimal points...

library(networkD3)

links <-
  read.table(header = TRUE, stringsAsFactors = FALSE, text = "
  source  target  value
  0       1       1.4
  1       2       2.9
  ")

nodes <-
  read.table(header = TRUE, stringsAsFactors = FALSE, text = "
  name
  A
  B
  C
  ")

sn <- sankeyNetwork(
  Links = links, 
  Nodes = nodes, 
  Source = 'source',
  Target = 'target', 
  Value = 'value', 
  NodeID = 'name'
  )

javascript_string <- 
  'function(el, x){
    d3.select(el).selectAll(".node text")
      .text(d => d.name + " (" + d3.format("(.0f")(d.value) + ")");
  }'

htmlwidgets::onRender(
  x = sn, 
  jsCode = javascript_string
)

enter image description here

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