0

I created this sankey network:

library(networkD3)
library(htmlwidgets)
library(data.table)

set.seed(1999)
links <- data.table(
  src = rep(0:4, times=c(1,1,2,3,5)),
  target = sample(1:11, 12, TRUE),
  value = sample(100, 12)
)[src < target, ]  # no loops
nodes <- data.table(name=LETTERS[1:12])

## Add text to label
txt <- links[, .(total = sum(value)), by=c('target')]
nodes[txt$target+1L, name := paste0(name, '<br>(', txt$total, ')')]

## Displays the counts as part of the labels
sn <- sankeyNetwork(Links=links, Nodes=nodes, Source='src', Target='target',
              Value='value', NodeID='name', fontSize=16, nodeWidth=50, width=600, height=300)

onRender(sn,
         '
  function(el,x) {
    d3.selectAll(".node text").remove()
    d3.selectAll(".node")
      .append("foreignObject")
      .attr("width", 100)
      .attr("height", 50)
      .html(function(d) { return d.name; })
  }
  '
)

enter image description here

I really would like to center the labels within the boxes, horizintally and vertially and also make the two lines center aligned. Can you help me?

CJ Yetman
  • 8,373
  • 2
  • 24
  • 56
Ai4l2s
  • 525
  • 2
  • 9

1 Answers1

0

Not sure what the best, most compatible CSS styling would be, but this works for me...

onRender(sn,
  '
  function(el, x) {
    d3.selectAll(".node text").remove();
    d3.selectAll(".node")
      .append("foreignObject")
      .attr("width", d => d.dx)
      .attr("height", d => d.dy)
      .html(d => "<div style=\\"height: 100%; display: flex; align-items: center; flex-direction: row; justify-content: center; text-align: center;\\">" + d.name);
  }
  '
)

enter image description here

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