I'm working on building a treemap in d3 v5 based on this example: https://www.d3indepth.com/layouts/
I can use the score data point for the color scale on the lowest level children, but I'd like the parents of the boxes above to have an average of the children below.
A sample of my data is here:
{
"name": "Unit",
"children": [
{
"name": "SBU",
"children": [
{
"name": "App",
"value": 3000,
"score": 0.5
},
{
"name": "App",
"value": 3500,
"score": 0.1
},
{
"name": "App",
"value": 2000,
"score": 0.9
}
]
}
Code below:
d3.json("health.json").then(function(data) {
console.log(data)
var treemapLayout = d3.treemap()
.size([1700, 1500])
.paddingOuter(16);
var rootNode = d3.hierarchy(data)
// Determine the size and placement of the boxes
rootNode
.sum(function(d) { return d.value; })
.sort(function(a,b) { return b.value - a.value; });
treemapLayout(rootNode);
var nodes = d3.select('svg g')
.selectAll('g')
.data(rootNode.descendants())
.enter()
.append('g')
.attr('transform', function(d) {return 'translate(' + [d.x0, d.y0] + ')'})
nodes
.append('rect')
.attr('width', function(d) { return d.x1 - d.x0; })
.attr('height', function(d) { return d.y1 - d.y0; })
.attr('style', function(d) {
return ('fill:' + d3.interpolateRdYlGn(d.data.health))
})
nodes
.append('text')
.attr('dx', 4)
.attr('dy', 14)
.text(function(d) {
return d.data.name;
})
});
One way you could do it is to preprocess the data to include the parent nodes' average child score, and the color for each node:
Calculate the average child score for each of the parent nodes, and add the result to your data-structure.
{
"name": "SBU",
"avgScore": 0.5,
"children: [
Use a sequential scale to map these average results to a particular color in e.g. d3.interpolateRdYlGn, and add the result to the data:
const colorScale = d3.scaleSequential(d3.interpolateRdYlGn)
.domain([0, 1]); // depending on your data
const nodeColor = colorScale(data.parent.avgScore);
{
"name": "SBU",
"avgScore": 0.5,
"nodeColor": nodeColor
}
You could then assign specific colors to the data for the root and child nodes:
const childNodeColor = rgb(100, 200, 100);
{
// Child node
...,
nodeColor: childNodeColor
}
Then simply render the color for each node in your tree using:
...
.attr('style', function(d) {
return colorScale(d.nodeColor);
});
Related
I would like fore-directed graph stop the internal tick after alpha < .5. but below code doesn't work, the alpha value always 1.
forwardAlpha(force,.5,1000)
function forwardAlpha(force, alpha, max) {
var i = 0;
while(force.alpha() > alpha && i++ < max) {
//console.log(force.alpha())
}
console.log(force.alpha())
force.stop()
}
What's proper way to stop the internal tick after graph is stable?
console.clear()
var data = {
"nodes": [{
"name": "Ben",
},{
"name": "May",
}, {
"name": "Jack",
}, {
"name": "Liam",
},{
"name": "Francis",
}, {
"name": "Owen",
}, {
"name": "Blake",
}, {
"name": "Julia",
}],
"edges": [{
"source": "Ben",
"target": "May"
}, {
"source": "Ben",
"target": "Blake"
}, {
"source": "Ben",
"target": "Owen"
}, {
"source": "Owen",
"target": "Julia"
}]
};
data.nodes.forEach(function(d, i) {
d.group = i
});
data.nodes.forEach(function(d) {
data.edges.forEach(function(e) {
if (e.source === d.name || e.target === d.name) {
data.nodes.find(function(f) {
return f.name === e.source
}).group = d.group;
data.nodes.find(function(f) {
return f.name === e.target
}).group = d.group;
}
})
})
var svg = d3.select("body").append('svg')
.style('border','5px solid red')
var edges = svg.selectAll("line")
.data(data.edges)
.enter()
.append("line")
.style("stroke", "#aaa")
.style("stroke-width", 2);
var color = d3.scaleOrdinal(d3.schemeCategory10);
var nodes = svg.selectAll("circle")
.data(data.nodes)
.enter()
.append("circle")
.attr("r", 10)
.style("stroke", "#444")
.style("stroke-width", 2)
.style("fill", function(d) {
return color(d.group);
})
var force = d3.forceSimulation()
.force("link", d3.forceLink()
.id(function(d) {
return d.name
}))
.force("charge", d3.forceManyBody().strength(-5))
.force("collide", d3.forceCollide(15))
.force("center", d3.forceCenter(150, 70))
force.nodes(data.nodes)
.force("link")
.links(data.edges);
force.on("tick", ticked);
forwardAlpha(force,.5,1000)
function forwardAlpha(force, alpha, max) {
var i = 0;
while(force.alpha() > alpha && i++ < max) {
//console.log(force.alpha())
}
console.log(force.alpha())
force.stop()
}
function ticked() {
edges.attr("x1", function(d) {
return d.source.x;
})
.attr("y1", function(d) {
return d.source.y;
})
.attr("x2", function(d) {
return d.target.x;
})
.attr("y2", function(d) {
return d.target.y;
})
nodes.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.7.0/d3.min.js"></script>
I am Trying to display my full svg tree within the display in a center view.
var svg = d3.select("body").append("svg")
.call(d3.zoom().on("zoom", function () {
svg.attr("transform", d3.event.transform);
})).on("dblclick.zoom", null)
.attr("width", "1000")
.attr("height",590)
.append("g")
svg.attr("transform",function(d) {
return "translate(" + 450 + "," + svgHeight + ") scale(" + scale + ")";
} );
I am adjusting the scale and height properties of the transform depends on the number of nodes, actually its working fine.
The problem is when I am trying to zoom in/out on the tree for the first time , its not zooming the focused node.
This occurs only when I am doing zoom for first time, from second time its zooming the pointing node.
This is what I tried so far : Codepen
A drawback of the otherwise solid solution #soundquiet posted is that it disrupts panning behaviour, leading to some sort of rapid shifting of the nodes.
A simpler, and more robust solution is shown below. I just wrap the g-element inside another g element called zoomContainer and call all zoom behaviour on that instead.
var treeData = {
"name": "Share point Server 2019",
"id": "a093F0000078Id5QAE",
"children": [{
"name": "is extended by",
"level": "sub node",
"children": [{
"name": "Share point Server 2019",
"id": "a093F0000078Id5QAE"
}]
}, {
"name": "manages",
"level": "sub node",
"children": [{
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}, {
"name": "HPE ProLiant ML350 Tower",
"id": "a093F0000078IcHQAU"
}]
}, {
"name": "is operated by",
"level": "sub node",
"children": [{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
}]
}]
};
var scale = 1,
svgHeight = 200,
nodeCount = 13;;
var margin = {
top: 20,
right: 90,
bottom: 30,
left: 90
},
width = window.outerWidth,
height = window.outerHeight;
var focused = false;
console.log('scale', scale)
var zoomContainer = d3.select("body").append("svg")
.call(d3.zoom().on("zoom", function() {
zoomContainer.attr("transform", d3.event.transform);
})).on("dblclick.zoom", null)
.attr("width", "1000")
.attr("height", 590)
.append("g")
var svg = zoomContainer
.append("g")
.attr("transform", function(d) {
return "translate(" +
(450) + "," + (svgHeight) + ") scale(" + scale + ")";
});
var i = 0,
duration = 750,
root;
// declares a tree layout and assigns the size
var treemap = d3.tree().size([height, width]);
// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function(d) {
return d.children;
});
root.x0 = height;
root.y0 = 0;
// Collapse after the second level
if (typeof collapse === 'undefined')
root.children.forEach(collapse);
update(root);
// Collapse the node and all it's children
function collapse(d) {
if (d.children) {
d._children = d.children
d._children.forEach(collapse)
d.children = null
}
}
function update(source) {
// Assigns the x and y position for the nodes
var treeData = treemap(root);
// Compute the new tree layout.
var nodes = treeData.descendants(),
links = treeData.descendants().slice(1);
let left = root;
let right = root;
var dx = ((nodeCount * 18) / 1000);
// Normalize for fixed-depth.
nodes.forEach(function(d, index) {
d.y = d.depth * 180;
d.x = d.x * ((nodeCount * 18) / 1000);
});
// ****************** Nodes section ***************************
// Update the nodes...
var node = svg.selectAll('g.node')
.data(nodes, function(d) {
return d.id || (d.id = ++i);
});
// Enter any new modes at the parent's previous position.
var nodeEnter = node.enter().append('g')
.attr('class', 'node')
.attr("transform", function(d) {
return "translate(" + (source.y0) + "," + (source.x0) + ")";
})
.on('click', d => {
// d3.event.preventDefault();
component.set("v.nodeName", d.data.name);
})
.on("dblclick", click);
// Add Circle for the nodes
nodeEnter.append('circle')
.attr('class', 'node')
.attr('r', 1e-6)
.style('stroke', 'steelblue')
.style('stroke-width', '3px');
// Add labels for the nodes
nodeEnter.append('text')
.attr("dy", ".35em")
.attr("x", function(d) {
return d.children || d._children ? -13 : 13;
})
.attr("text-anchor", function(d) {
return d.children || d._children ? "end" : "start";
})
.text(function(d) {
return d.data.name;
});
// UPDATE
var nodeUpdate = nodeEnter.merge(node);
// Transition to the proper position for the node
nodeUpdate.transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + (d.y) + "," + (d.x) + ")";
});
// Update the node attributes and style
nodeUpdate.select('circle.node')
.attr('r', 3)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
})
.attr('cursor', 'pointer');
// Remove any exiting nodes
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + (source.y) + "," + source.x + ")";
})
.remove();
// On exit reduce the node circles size to 0
nodeExit.select('circle')
.attr('r', 1e-6);
// On exit reduce the opacity of text labels
nodeExit.select('text')
.style('fill-opacity', 1e-6);
// ****************** links section ***************************
// Update the links...
var link = svg.selectAll('path.link')
.data(links, function(d) {
return d.id;
});
// Enter any new links at the parent's previous position.
var linkEnter = link.enter().insert('path', "g")
.attr("class", "link")
.style('fill', "none")
.style('stroke', "#ccc")
.style('stroke-width', "2px")
.attr('d', function(d) {
var o = {
x: source.x0,
y: source.y0
}
return diagonal(o, o)
});
// UPDATE
var linkUpdate = linkEnter.merge(link);
// Transition back to the parent element position
linkUpdate.transition()
.duration(duration)
.attr('d', function(d) {
return diagonal(d, d.parent)
});
// Remove any exiting links
var linkExit = link.exit().transition()
.duration(duration)
.attr('d', function(d) {
var o = {
x: source.x,
y: source.y
}
return diagonal(o, o)
})
.remove();
// Store the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
// Creates a curved (diagonal) path from parent to the child nodes
function diagonal(s, d) {
var path = "M" + d.y + "," + d.x +
"C" + (d.y + s.y) / 2 + "," + d.x +
" " + (d.y + s.y) / 2 + "," + s.x +
" " + s.y + "," + s.x;
return path;
}
// Toggle children on click.
function click(d) {
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<div style="background:white" id="body"></div>
Problem: highlighted text(in the image below) is been over-written(therefore its looking bold) when the node is expanded.
Expected Output:
Collapsible d3 Treechart
var linktext = svg.selectAll("g.link")
.data(links, function (d) {
console.log("Text Data Id..."+d.id);
return d.id;
});
linktext.enter()
.insert("g")
.merge(linktext)
.attr("class", "link")
.attr("transform", function (d) {
return "translate(" + ((d.parent.y + d.y) / 2) + "," + ((d.parent.x +d.x) / 2) + ")"; })
.append("text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function (d) {
debugger;
console.log("Text Data Rule..."+d.data.rule);
return d.data.rule;
});
linktext.exit().transition()
.remove();
Your problem is caused due to .merge function, this code will fix the multiple-element issue
var treeData =
{ "name": "E", "children": [{ "name": "A", "rule": "yes", "children": [{ "name": "B", "rule": "<=3.843750000000001", "children": [{ "name": "C", "rule": "yes" }, { "name": "D", "rule": "no", "children": [{ "name": "Sex", "rule": "yes", "children": [{ "name": "E", "rule": "Male", "children": [{ "name": "F", "rule": "<=62.5125" }, { "name": "G", "rule": ">62.5125", "children": [{ "name": "H", "rule": "yes" }, { "name": "K", "rule": "no" }] }] }, { "name": "I", "rule": "Female" }] }, { "name": "J", "rule": "no" }] }] }, { "name": "K", "rule": ">3.843750000000001", "children": [{ "name": "Q", "rule": "yes" }, { "name": "H", "rule": "no", "children": [{ "name": "S", "rule": "yes" }, { "name": "N", "rule": "no" }] }] }] }, { "name": "L", "rule": "no", "children": [{ "name": "S", "rule": "yes", "children": [{ "name": "T", "rule": "<=82.025", "children": [{ "name": "Y", "rule": "<=102.9125" }, { "name": "Malaise", "rule": ">102.9125", "children": [{ "name": "Age", "rule": "no", "children": [{ "name": "J", "rule": ">40.6625", "children": [{ "name": "M", "rule": "yes", "children": [{ "name": "N", "rule": "no", "children": [{ "name": "G", "rule": "yes" }, { "name": "E", "rule": "no" }] }] }] }] }] }] }] }, { "name": "survive", "rule": "no" }] }] };
// Set the dimensions and margins of the diagram
var margin = { top: 20, right: 90, bottom: 30, left: 90 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// append the svg object to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate("
+ margin.left + "," + margin.top + ")");
var i = 0,
duration = 750,
root;
// declares a tree layout and assigns the size
var treemap = d3.tree().size([height, width]);
// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function (d) { return d.children; });
root.x0 = height / 2;
root.y0 = 0;
// Collapse after the second level
root.children.forEach(collapse);
update(root);
// Collapse the node and all it's children
function collapse(d) {
if (d.children) {
d._children = d.children
d._children.forEach(collapse)
d.children = null
}
}
function update(source) {
// Assigns the x and y position for the nodes
var treeData = treemap(root);
// Compute the new tree layout.
var nodes = treeData.descendants(),
links = treeData.descendants().slice(1);
// Normalize for fixed-depth.
nodes.forEach(function (d) { d.y = d.depth * 180 });
// ****************** Nodes section ***************************
// Update the nodes...
var node = svg.selectAll('g.node')
.data(nodes, function (d) { return d.id || (d.id = ++i); });
// Enter any new modes at the parent's previous position.
var nodeEnter = node.enter().append('g')
.attr('class', 'node')
.attr("transform", function (d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on('click', click);
// Add Circle for the nodes
nodeEnter.append('circle')
.attr('class', 'node')
.attr('r', 1e-6)
.style("fill", function (d) {
return d._children ? "lightsteelblue" : "#fff";
});
// Add labels for the nodes
nodeEnter.append('text')
.attr("dy", ".35em")
.attr("x", function (d) {
return d.children || d._children ? -13 : 13;
})
.attr("text-anchor", function (d) {
return d.children || d._children ? "end" : "start";
})
.text(function (d) { return d.data.name; });
// UPDATE
var nodeUpdate = nodeEnter.merge(node);
// Transition to the proper position for the node
nodeUpdate.transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + d.y + "," + d.x + ")";
});
// Update the node attributes and style
nodeUpdate.select('circle.node')
.attr('r', 10)
.style("fill", function (d) {
return d._children ? "lightsteelblue" : "#fff";
})
.attr('cursor', 'pointer');
// Remove any exiting nodes
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
// On exit reduce the node circles size to 0
nodeExit.select('circle')
.attr('r', 1e-6);
// On exit reduce the opacity of text labels
nodeExit.select('text')
.style('fill-opacity', 1e-6);
// ****************** links section ***************************
// Update the links...
var link = svg.selectAll('path.link')
.data(links, function (d) { return d.id; });
// Enter any new links at the parent's previous position.
var linkEnter = link.enter().insert('path', "g")
.attr("class", "link")
.attr('d', function (d) {
var o = { x: source.x0, y: source.y0 }
return diagonal(o, o)
});
// UPDATE
var linkUpdate = linkEnter.merge(link);
// Transition back to the parent element position
linkUpdate.transition()
.duration(duration)
.attr('d', function (d) { return diagonal(d, d.parent) });
// Remove any exiting links
link.exit().transition()
.duration(duration)
.attr('d', function (d) {
var o = { x: source.x, y: source.y }
return diagonal(o, o)
})
.remove();
var linktext = svg.selectAll("g.link")
.data(links, function (d) {
return d.id;
});
linktext.enter()
.insert("g")
//.merge(linktext)
.attr("class", "link")
.attr("transform", function (d) {
return "translate(" + ((d.parent.y + d.y) / 2) + "," + ((d.parent.x + d.x) / 2) + ")";
})
.append("text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function (d) {
return d.data.rule;
});
linktext.exit().remove();
// Store the old positions for transition.
nodes.forEach(function (d) {
d.x0 = d.x;
d.y0 = d.y;
});
// Creates a curved (diagonal) path from parent to the child nodes
function diagonal(s, d) {
path = `M ${s.y} ${s.x}
C ${(s.y + d.y) / 2} ${s.x},
${(s.y + d.y) / 2} ${d.x},
${d.y} ${d.x}`
return path
}
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
Also replace your css with the below to fix the link-text font:
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
path.link {
fill: none;
stroke: #000;
stroke-width: 1px;
}
I am trying to create a sunburst chart in d3js and would like each item/node to be of a specific color that is read off the json file that holds the hierarchy. Have looked at many examples in the d3js community but never found a clear answer. Thanks!
Here is my json (flare2.json) file:
{
"name": "Root","color": "#c0e2f1",
"children": [
{
"name": "T1","color": "#a3a3a3",
"children": [
{"name": "S1", "size": 3938, "color": "#a9a9a9"},
{"name": "D1","size": 3238, "color": "#ef69b4"}
]
},
{
"name": "T2", "color": "#c0e2f1"
}
]
}
Here is the javascript snippet that calls the json:
d3.json("flare2.json", function(error, root) {
var g = svg.selectAll("g")
.data(partition.nodes(root))
.enter().append("g");
var color = d3.scale.ordinal();
var path = g.append("path")
.attr("d", arc)
//.style("fill", function(d) { return colors((d.children ? d : d.parent).name); })
.style("fill", function(d) { return color(d.color); })
.on("click", click);
}
I think you're possibly making this too hard. The following line
.style("fill", function(d) { return color(d.color); })
Seems like it doesn't need to use a color function, but rather just return the object's color property, like so:
.style("fill", function(d) { return d.color; })
Im trying to make a hierarchical edge bundling like this using d3 v4. I use d3.curveBundle to make the line curved. But in my project, the line doesn't seem to be curved.
What I get is a straight line like this:
This is my code:
var data = {
"name": "Eve",
"children": [
{
"name": "Cain"
},
{
"name": "Seth",
"children": [
{
"name": "Enos"
},
{
"name": "Noam"
}
]
},
{
"name": "Abel"
},
{
"name": "Awan",
"children": [
{
"name": "Enoch"
}
]
},
{
"name": "Azura"
}
]
};
var cluster = d3.cluster()
.size([360, 120]);
var nodes = cluster(d3.hierarchy(data));
var links = nodes.links();
var svg = d3.select("div.radial-network")
.append("svg")
.attr("width", "100%")
.attr("height", "300")
.attr("transform", "translate(120,120)");
const line = d3.radialLine()
.curve(d3.curveBundle.beta(0.95))
.angle(function(d,i){ return d.x*Math.PI/180;})
.radius(function(d,i) {return d.y;});
const edges = svg.selectAll('.link').data(links);
edges.enter().append('path')
.attr('class', 'link')
.attr('stroke', 'red')
.attr('d', function(d, i) {return line(d.source.path(d.target));});