I was trying to add link labels to a sankey diagram as described by CJ Yetman in:
In R, how to display value on the links/paths of Sankey Graph?
library(htmlwidgets)
library(networkD3)
nodes <- data.frame(name = c("Node A", "Node B", "Node C", "Node D"))
links <- data.frame(
source = c(0, 0, 1, 2),
target = c(1, 2, 3, 3),
value = c(10, 20, 30, 40))
p <- sankeyNetwork(
Links = links, Nodes = nodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
fontSize = 20, nodeWidth = 30)
htmlwidgets::onRender(p, '
function(el) {
var nodeWidth = this.sankey.nodeWidth();
var links = this.sankey.links();
links.forEach((d, i) => {
var startX = d.source.x + nodeWidth;
var endX = d.target.x;
var startY = d.source.y + d.sy + d.dy / 2;
var endY = d.target.y + d.ty + d.dy / 2;
d3.select(el).select("svg g")
.append("text")
.attr("text-anchor", "middle")
.attr("alignment-baseline", "middle")
.attr("x", startX + ((endX - startX) / 2))
.attr("y", startY + ((endY - startY) / 2))
.text(d.value);
})
}
')
Now I want to change the font size of the labels. Also I would like to add axis labels and change the node labels to vertical labels.