I have a hierarchy layout as shown in the image below where the 3rd layer of nodes contains words that are quite long so I want to give these nodes more space to their left to make it easier to read. But I am not sure what to change to do so.
Code for the node, path and the text:
JavaScript
x
72
72
1
const root = hierarchy(investmentByLocationData).sort(
2
(a, b) =>
3
descending(a.height, b.height) || ascending(a.data.name, b.data.name)
4
);
5
6
root.dx = 12;
7
root.dy = width / (root.height + 1);
8
cluster().nodeSize([root.dx, root.dy])(root);
9
10
const linkGenerator = linkHorizontal()
11
.x((node) => node.y)
12
.y((node) => node.x);
13
14
svg
15
.selectAll(".node")
16
.data(root.descendants())
17
.join((enter) =>
18
enter
19
.append("circle")
20
.attr("fill", (d) => (d.children ? "#555" : "#999"))
21
)
22
.attr("r", 2.5)
23
.attr("class", "node")
24
.attr("cx", (node) => node.y)
25
.attr("cy", (node) => node.x)
26
.attr("r", 2.5)
27
.transition()
28
.duration(500)
29
.delay((node) => node.depth * 300)
30
.attr("opacity", 1);
31
32
// links
33
const enteringAndUpdatingLinks = svg
34
.selectAll(".path")
35
.data(root.links())
36
.join("path")
37
.attr("class", "link")
38
.attr("d", linkGenerator)
39
.attr("stroke-dasharray", function() {
40
const length = this.getTotalLength();
41
return `${length} ${length}`;
42
})
43
.attr("stroke", "black")
44
.attr("fill", "none")
45
.attr("stroke-opacity", 0.5)
46
.attr("stroke-linejoin", "round")
47
.attr("stroke-width", 0.4);
48
49
if (data !== previouslyRenderedData) {
50
enteringAndUpdatingLinks
51
.attr("stroke-dashoffset", function() {
52
return this.getTotalLength();
53
})
54
.transition()
55
.duration(500)
56
.delay((link) => link.source.depth * 500)
57
.attr("stroke-dashoffset", 5);
58
}
59
60
//labels
61
svg
62
.selectAll(".text")
63
.data(root.descendants())
64
.join("text")
65
.attr("x", (d) => d.y)
66
.attr("y", (d) => d.x)
67
.attr("dy", "0.31em")
68
.attr("dx", (d) => (d.children ? -6 : 6))
69
.text((d) => (d.children ? d.data.name : d.data.funding))
70
.attr("text-anchor", (d) => (d.children ? "end" : "start"))
71
.attr("font-size", (d) => (d.children ? 15 : 14));
72
Advertisement
Answer
After tinkering around with it I managed to solve it by altering root.dx
and root.dy
.
JavaScript
1
3
1
root.dx = 18;
2
root.dy = width / (root.height * 0.6);
3