0

I want to add a dollar sign to the link and node labels in a networkD3 Sankey plot. A similar question has be asked and answered here:

Link value label thousands separator

In the above link, CJ rewrites the link titles with htmlwidgets::onRender to change the thousands separator from "," to ".".

I unfortunately do not understand JavaScript and can not figure out how to change the solution to fit my problem.

EDIT

Trying to apply CJ Yetman's technique to nodes. My code is not working.

customJS <- '
function(el,x) {
    var node = d3.selectAll(".node");

    var format = d3.format("($,.2f");

    node.select("title").select("body")
        .html(function(d) { return "<pre>" + d.target.name + "<br>" + format(d.value) + "<pre>"; });
}
' 

Suggestions and corrections welcome.

2 Answers2

0

For nodes, you can add "$" to the strings in your data frame before it's passed to sankeyNetwork(), like...

nodes <- data.frame(name = c("$a", "$b"))

For links, you can adjust the format string (format specification documented here) to whatever you need in the JavaScript command here...

var format = d3.format("$");

all together, that looks like this...

library(networkD3)
library(htmlwidgets)

nodes <- data.frame(name = c("$a", "$b"))
links <- data.frame(source = c(0), target = c(1), value = c(12000))

p <- sankeyNetwork(
  Links = links,
  Source = "source",
  Target = "target",
  Value = "value",
  Nodes = nodes,
  NodeID = "name",
  fontSize = 12,
  nodeWidth = 30,
  iterations = 0
)

customJS <- '
function(el,x) { 
    var link = d3.selectAll(".link");

    var format = d3.format("$");

    link.select("title").select("body")
        .html(function(d) { return "<pre>" + d.source.name + " \u2192 " + d.target.name +
            "\\n" + format(d.value) + "<pre>"; });
}
'

onRender(p, customJS)

enter image description here

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

Using CJ Yetman's code I changed the var format to get the format below.

Original    ->    CJ Yetman    ->    My Edit
12000      ->      $12000        ->    $12,000.00

customJS <- '
function(el,x) {
    var link = d3.selectAll(".link");

    var format = d3.format("($,.2f");

    link.select("title").select("body")
        .html(function(d) { return "<pre>" + d.source.name + " \u2192 " + d.target.name +
            "\\n" + format(d.value) + "<pre>"; });
}
'

I also used CJ Yetman's answer here to use onRender to apply the customJS in shiny.