I am trying to display my full tree within fixed height and width.
Since I dont know the exact nodes count , tree nodes went out of focus.
I have tried to adjust the zoom scale (manually) to display within the boundaries.
I just want to adjust the zoom scale automatically depends on the nodes count
Can anyone help me to sortout this issue.
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"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
},
{
"name": "Power point SH-20",
"id": "a093F00000794ZWQAY"
}
]
}
]
};
var nodeCount = 53;
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 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", 800)
.append("g")
svg.attr("transform", function(d) {
return "translate(" +
(450) + "," + (svgHeight) + ")scale(" + scale + ")";
});
var nodeCount = 15;
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) {
}
}
body {
font: 10px sans-serif;
margin: 50px;
}
.grid .tick {
stroke: lightgrey;
opacity: 0.7;
shape-rendering: crispEdges;
}
.grid path {
stroke-width: 0;
}
.axis path {
fill: none;
stroke: #bbb;
shape-rendering: crispEdges;
}
.axis text {
fill: #555;
}
.axis line {
stroke: #e7e7e7;
shape-rendering: crispEdges;
}
.axis .axis-label {
font-size: 14px;
}
.line {
fill: none;
stroke-width: 1.5px;
}
.dot {
/* consider the stroke-with the mouse detect radius? */
stroke: transparent;
stroke-width: 10px;
cursor: pointer;
}
.dot:hover {
stroke: rgba(68, 127, 255, 0.3);
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div style="background:white" id="body"></div>
Related
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>
I am trying to make a sunburst by following the 3-part tutorial on https://bl.ocks.org/denjn5/3b74baf5edc4ac93d5e487136481c601 My json contains sell information based on country and product division. I am trying to show in the first layer sell based on country and in the 2nd layer sell based on product division. My Json file looks like this:
{
"country": "All",
"shares":[
{
"country": "at",
"shares":[
{
"productdivision": "accessorie",
"label": 53222
},
{
"productdivision": "apparel",
"label": 365712
},
{
"productdivision": "footwear",
"label": 523684
}
]
},
{
"country": "be",
"shares":[
{
"productdivision": "accessorie",
"label": 57522
},
{
"productdivision": "apparel",
"label": 598712
},
{
"productdivision": "footwear",
"label": 52284
}
]
},
{
"country": "DE",
"shares":[
{
"productdivision": "accessorie",
"label": 56982
},
{
"productdivision": "apparel",
"label": 55312
},
{
"productdivision": "footwear",
"label": 67284
}
]
},
{
"country": "Fr",
"shares":[
{
"productdivision": "accessorie",
"label": 5862
},
{
"productdivision": "apparel",
"label": 45312
},
{
"productdivision": "footwear",
"label": 26284
}
]
}
]
}
This json file's name is kpiDrillDown2.json and I call it in my code with d3.json(). I have made slight changes to the code to work for my data. The code is as follows:
<html>
<head>
<style>
#import url('https://fonts.googleapis.com/css?family=Raleway');
body {
font-family: "Raleway", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<svg></svg>
<script>
//initialize variables
var width = 500;
var height = 500;
var radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal(d3.schemeCategory20b);
//setting up svg workspace
var g = d3.select('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
//formatting the data
var partition = d3.partition()
.size([2 * Math.PI, radius]);
function draw(nodeData){
debugger;
//finding the root node
var root = d3.hierarchy(nodeData)
.sum(function (d) { return d.label});
//calculating each arc
partition(root);
var arc = d3.arc()
.startAngle(function (d) { return d.x0; })
.endAngle(function (d) { return d.x1; })
.innerRadius(function (d) { return d.y0; })
.outerRadius(function (d) { return d.y1; });
g.selectAll('g')
.data(root.descendants())
.enter()
.append('g')
.attr("class", "node")
.append('path')
.attr("display", function (d) { return d.depth ? null : "none"; })
.attr("d", arc)
.style('stroke', '#fff')
.style("fill", function (d) { return color((d.parent ? d : d.parent).data.productdivision); })
g.selectAll(".node")
.append("text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")rotate(" + computeTextRotation(d) + ")"; })
.attr("dx", "-20")
.attr("dy", ".5em")
.text(function(d) { return d.parent ? d.data.productdivision : "" });
function computeTextRotation(d) {
var angle = (d.x0 + d.x1) / Math.PI * 90;
// Avoid upside-down labels
return (angle < 90 || angle > 270) ? angle : angle + 180;
}
}
d3.json('kpiDrillDown3.json', draw);
</script>
</body>
</html>
I put a debbuger in the draw functin to inspect root element. Root doesn't have any children. This is what I see in the console:
When I continue it gives me the error:"Cannot read property 'data' of null". As shown in console, root doesn't have children. My question is, do I need to change my json data format to make root recogninze the chilren, or am I doing something wrong. I am new to d3js and basically by getting the source code and modifying it, I am making my way through. This is the error in console:
I appreciate your help and thank you very much.
According to the API:
The specified children accessor function is invoked for each datum, starting with the root data, and must return an array of data representing the children, or null if the current datum has no children. If children is not specified, it defaults to:
function children(d) {
return d.children;
}
However, in your data structure, you don't have children, but shares instead.
So, the hierarchy should be:
var root = d3.hierarchy(data, function(d) {
return d.shares;
})
Pay attention to the fact that in the JSON of that tutorial you linked (just like in the API's example) the children's array is named children.
Here is a demo, look at the console (your browser's console, not the snippet one):
var data = {
"country": "All",
"shares": [{
"country": "at",
"shares": [{
"productdivision": "accessorie",
"label": 53222
},
{
"productdivision": "apparel",
"label": 365712
},
{
"productdivision": "footwear",
"label": 523684
}
]
},
{
"country": "be",
"shares": [{
"productdivision": "accessorie",
"label": 57522
},
{
"productdivision": "apparel",
"label": 598712
},
{
"productdivision": "footwear",
"label": 52284
}
]
},
{
"country": "DE",
"shares": [{
"productdivision": "accessorie",
"label": 56982
},
{
"productdivision": "apparel",
"label": 55312
},
{
"productdivision": "footwear",
"label": 67284
}
]
},
{
"country": "Fr",
"shares": [{
"productdivision": "accessorie",
"label": 5862
},
{
"productdivision": "apparel",
"label": 45312
},
{
"productdivision": "footwear",
"label": 26284
}
]
}
]
};
var root = d3.hierarchy(data, function(d) {
return d.shares;
})
.sum(function(d) {
return d.label
});
console.log(root)
<script src="https://d3js.org/d3.v4.min.js"></script>
I'm new to D3 js. I would like to draw a tree structure using d3. However, I want the paths between my nodes to be flexible unlike the usual diagonal and projection methods. I need connections between the nodes to be like this:
How do I do this in d3?
This is my current code with diagonal.
<html>
<head>
<title> Box office </title>
</head>
<body>
<style>
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id = "boxoffice"></div>
<script type="text/javascript">
var sampleData = [
{
"ChangeFlowsFromParent": "false",
"ChangeFlowsToParent": "false",
"StreamType": "Mainline",
"streamName": "ArgOS_2_0",
"Parent": "none",
"Compliance": "Released",
"children": [
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Development",
"streamName": "ArgOS_2_0_DHAL",
"Parent": "ArgOS_2_0",
"Compliance": "Released"
},
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Development",
"streamName": "ArgOS_2_0_Dev",
"Parent": "ArgOS_2_0",
"Compliance": "Released",
"children": [
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Release",
"streamName": "r_ArgOS_0230",
"Parent": "ArgOS_2_0_Dev",
"Compliance": "Released"
},
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Release",
"streamName": "branch1",
"Parent": "ArgOS_2_0_Dev",
"Compliance": "Released",
"children": [
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Release",
"streamName": "branch100",
"Parent": "branch1",
"Compliance": "Released"
},
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Release",
"streamName": "branch200",
"Parent": "branch1",
"Compliance": "Released",
"children": [
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Release",
"streamName": "honey",
"Parent": "branch200",
"Compliance": "Released"
}
]
}
]
}
]
},
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Development",
"streamName": "ArgOS_2_0_IPC-Tracer",
"Parent": "ArgOS_2_0",
"Compliance": "Released",
"children": [
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Release",
"streamName": "ArgOS_2_0_IPC_child 1",
"Parent": "ArgOS_2_0_IPC",
"Compliance": "Released"
},
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Release",
"streamName": "ArgOS_2_0_IPC_child 2",
"Parent": "ArgOS_2_0_IPC",
"Compliance": "Released"
}
]
},
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Development",
"streamName": "ArgOS_2_0_NSW_Temp",
"Parent": "ArgOS_2_0",
"Compliance": "Released"
},
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Development",
"streamName": "ArgOS_2_0_Test",
"Parent": "ArgOS_2_0",
"Compliance": "Released"
},
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Development",
"streamName": "ArgOS_2_CBD",
"Parent": "ArgOS_2_0",
"Compliance": "Released"
},
{
"ChangeFlowsFromParent": "true",
"ChangeFlowsToParent": "true",
"StreamType": "Development",
"streamName": "test_mergewp",
"Parent": "ArgOS_2_0",
"Compliance": "Released"
}
]
}
]
var margin = {top:100, bottom: 100, left:100, right:100},
width = 1800 - margin.left-margin.right, //total width minus side margins
height = 1500 - margin.top - margin.bottom; //total height minus vertical margins
var tree = d3.layout.tree().size([width, height]);
tree.nodeSize([40,100]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.x, -d.y]; });
var svgContainer = d3.select("#boxoffice").append("svg").attr("width", width).attr("height", height).append("g").attr("transform", "translate(" + (width/2) + "," + (height - 500) + ")");
var root = sampleData[0];
root.x0 = width/2;
root.y0 = 0;
update(root);
d3.select(self.frameElement).style("height", "500px");
function update(sourceNode){
var nodes = tree.nodes(sourceNode).reverse(),
links = tree.links(nodes);
nodes.forEach(function(d){d.y = d.depth * 180});
var node = svgContainer.selectAll("g.node").attr("class", "node").data(nodes, function(d, i){return d.id || (d.id = ++i); });
var nodeEnter = node.enter().append("g")
.attr("transform", function(d) {
<!-- if(d.StreamType == "Mainline") -->
<!-- return "translate(-100,-100)"; -->
<!-- else -->
return "translate(" + sourceNode.y0 + "," + sourceNode.x0 + ")";
});
nodeEnter.append("circle")
.attr("r", 15)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -13 : 13; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.streamName; })
.style("fill-opacity", 1e-6);
var nodeUpdate = node.transition()
.duration(100)
.attr("transform", function(d) {
if(d.StreamType == "Mainline")
{
var lastElement = nodes[0];
return "translate(" + (lastElement.y + 100) + "," + (lastElement.x -130) + ")"; //adding the root element
}
else
return "translate(" + d.y + "," + (d.x-(margin.top + margin.bottom)) + ")";
});
nodeUpdate.select("circle")
.attr("r", 10)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1);
var link = svgContainer.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: sourceNode.x0, y: sourceNode.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(10)
.attr("d", diagonal);
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
function positionLink(d) {
return "M" + d[0].x + "," + d[0].y
+ "S" + d[1].x + "," + d[1].y
+ " " + d[2].x + "," + d[2].y;
}
</script>
</body>
</html>
As in this code, the links are all messy. I can tidy it up for diagonal path links, but I want my links to be dynamic and flexible. How can I achieve this?
It's unclear what you mean by "flexible". More accurate terminology can be gathered from https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Bezier_Curves . For example, you may want a cubic Bezier curve.
To implement this, you will need to alter this section of code:
.attr("d", function(d) {
var o = {x: sourceNode.x0, y: sourceNode.y0};
return diagonal({source: o, target: o});
More information can be found at this example, which seems to implement what you want:
https://bl.ocks.org/mbostock/4339184
It uses:
.attr("d", d3.linkHorizontal()
.x(function(d) { return d.y; })
.y(function(d) { return d.x; }));
The link capabilities are related, but not equivalent to the diagonal capabilities.
I am using d3 tree with more than 500 nodes(one root and 500/1000 child nodes to it in 2nd level). Arrows looks perfect up-to 50 child nodes but more than that on left and right side nodes, arrows shown at top of node and path are intersects node edge diagonally.
how to resolve this issue in such way that arrow should touch node where path intersect node?Nodes used are rectangular as given in this question Arrows are not touching to nodes in d3.js
All right, all right here's your solution. This is what I call the "back-off" approach. It's the same approach I used in this question. It works by fitting the path and then subtracting off of it the "radius" of your square plus marker head.
Couple things first, you only need to append the "marker" def once, it can be used on all the lines. Second, I switched the paths to draw top down, you had them drawing what I would all backwards - from child to parent. This requires additional rotation of the head.
Here's the code:
var width = 500;
var height = 500;
var nodeWidth = 40;
var nodeHeight = 40;
var circleRadius = 5;
var diagramLayout;
var graphData = {
"nodes": [{
"uid": "Term20",
"name": "Term20",
"image": "images/Term.png"
}, {
"uid": "glossforArrow",
"name": "glossforArrow",
"image": "images/Glossary.png"
}, {
"uid": "Term43",
"name": "Term43",
"image": "images/Term.png"
}, {
"uid": "Term1",
"name": "Term43",
"image": "images/Term.png"
}, {
"uid": "Term2",
"name": "Term43",
"image": "images/Term.png"
}],
"links": [{
"source": "glossforArrow",
"target": "Term20",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term43",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term1",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term3",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term4",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term5",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term6",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term7",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term8",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term9",
"direction": "output",
"label": "Owned Terms"
}, {
"source": "glossforArrow",
"target": "Term2",
"direction": "output",
"label": "Owned Terms"
}]
};
treeInitialize(graphData)
function treeInitialize(graphData) {
diagramLayout = d3.select("#diagramLayout")
.attr("id", "diagramLayout") //set id
.attr("width", width) //set width
.attr("height", height) //set height
.append("g")
.attr("transform", "translate(" + 20 + "," + 20 + ")")
markerRefx = 40;
var data2 = graphData.links.filter(function(l) {
if (l.target == undefined && l.source == undefined) {
return false;
} else {
return true;
}
});
data2.push(JSON.parse('{"target":"glossforArrow","source":""}'))
var treeData = d3.stratify().id(function(d) {
return d.target;
}).parentId(function(d) {
return d.source;
})(data2)
nodes = d3.hierarchy(treeData, function(d) {
return d.children;
});
var levelWidth = [1];
var childCount = function(level, n) {
if (n.children && n.children.length > 0) {
if (levelWidth.length <= level + 1) levelWidth.push(0);
levelWidth[level + 1] += n.children.length;
n.children.forEach(function(d) {
childCount(level + 1, d);
});
}
};
childCount(0, nodes);
newHeight = d3.max(levelWidth) * 100;
var tree = d3.tree().size([height, width])
tree.size([newHeight, height / 2]);
tree.separation(function(a, b) {
return a.parent == b.parent ? 50 : 100;
});
nodes = tree(nodes);
treeLayout(nodes);
function treeLayout(nodes) {
var node = diagramLayout.selectAll(".node");
node = node.data(nodes.descendants());
var link = diagramLayout.selectAll(".link")
.data(nodes.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.attr("fill", "none")
.attr("stroke", "#000")
.attr("stroke-width", "1px")
.attr("stroke-opacity", "0.3")
.attr("d", function(d) {
return connector(d.parent, d);
})
//nodes.descendants().slice(1).forEach(function(d) {
var mark = diagramLayout.append("svg:defs").selectAll("marker") //
.data(["start"]) // Different link/path types can be defined here
.enter().append("svg:marker") // This section adds in the arrows
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 0)
.attr("refY", 0)
.attr("markerWidth", 5)
.attr("markerHeight", 5)
.attr("orient", "auto")
.attr("stroke", "#000")
.attr("fill", "#000")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5")
.style("stroke-width", "0.3px")
//.attr("transform","rotate(180,5, 0)");
// });
link.attr("marker-end", "url(#start)")
.each(function(d, i, j) {
var self = d3.select(this),
t = this.getTotalLength(),
p = this.getPointAtLength(t - 25);
self.attr("d", connector(d.parent, p));
})
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("height", nodeHeight)
.attr("width", nodeWidth)
nodeEnter.attr("transform", function(d) {
return "translate(" + project(d.x, d.y) + ")";
})
var nodeIcon = nodeEnter.append("rect")
.attr("class", "rect")
.attr("x", -20)
.attr("y", -20)
.attr("rx", 10)
.attr("width", 40)
.attr("height", 40)
.attr("stroke-width", function(d) {
return Math.sqrt(2);
})
.attr("stroke-opacity", "0.3")
.attr("stroke", "#000")
.attr("fill", "none")
//wrap(nodeText, 8)
}
}
function connector(from, to) {
return "M" + project(from.x, from.y) + "C" + project(from.x, (from.y + to.y) / 2) + " " + project(to.x, (from.y + to.y) / 2) + " " + project(to.x, to.y);
}
function project(x, y) {
return [x, y];
}
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #000;
stroke-opacity: .6;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="mainScreen" style="height:100%;width:100%;position:absolute;">
<svg id="diagramLayout" style="height:100%;width:100%;position:absolute;">
</svg>
</div>
I am playing around with D3.js and I am trying to do two things:
On hovering of the lines, I want to apply a style to the lines (color to light blue or something). It can go to the parent node, or the highest level parent, either one would greatly help me out. If you know how to do both, please share!
On hovering of the text per each node, I would like to display a tooltip of the "test" attribute in the JSON data.
I have messed around with the tooltips before, but in this scenario I am not sure where to put the ,on("mouseover" event handler. This is also my first time testing out the d3.treeoption.
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 960 - margin.right - margin.left,
height = 800 - margin.top - margin.bottom;
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
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 root={ //json var root
"name": "flare",
"test": "blue",
"children": [{
"name": "analytics",
"test": "red",
"children": [{
"name": "cluster",
"test": "green",
"children": [{
"name": "AgglomerativeCluster",
"test": "blue",
"size": 3938
}, {
"name": "CommunityStructure",
"test": "yellow",
"size": 3812
}, {
"name": "HierarchicalCluster",
"test": "orange",
"size": 6714
}, {
"name": "MergeEdge",
"test": "someColor",
"size": 743
}]
}, {
"name": "graph",
"test": "someColor",
"children": [{
"name": "BetweennessCentrality",
"test": "someColor",
"size": 3534
}, {
"name": "LinkDistance",
"test": "someColor",
"size": 5731
}, {
"name": "MaxFlowMinCut",
"size": 7840
}, {
"name": "ShortestPaths",
"test": "someColor",
"size": 5914
}, {
"name": "SpanningTree",
"test": "someColor",
"size": 3416
}]
}, {
"name": "optimization",
"test": "someColor",
"children": [{
"name": "AspectRatioBanker",
"test": "someColor",
"size": 7074
}]
}]
}, {
"name": "animate",
"test": "someColor",
"children": [{
"name": "interpolate",
"test": "someColor",
"children": [{
"name": "ArrayInterpolator",
"test": "someColor",
"size": 1983
}, {
"name": "ColorInterpolator",
"test": "someColor",
"size": 2047
}, {
"name": "DateInterpolator",
"test": "someColor",
"size": 1375
}, {
"name": "Interpolator",
"test": "someColor",
"size": 8746
}, {
"name": "MatrixInterpolator",
"test": "someColor",
"size": 2202
}, {
"name": "NumberInterpolator",
"test": "someColor",
"size": 1382
}, {
"name": "ObjectInterpolator",
"test": "someColor",
"size": 1629
}, {
"name": "PointInterpolator",
"test": "someColor",
"size": 1675
}, {
"name": "RectangleInterpolator",
"test": "someColor",
"size": 2042
}]
}, {
"name": "ISchedulable",
"test": "someColor",
"size": 1041
}, {
"name": "Parallel",
"test": "someColor",
"size": 5176
}, {
"name": "Pause",
"test": "someColor",
"size": 449
}, {
"name": "Scheduler",
"test": "someColor",
"size": 5593
}, {
"name": "Sequence",
"test": "someColor",
"size": 5534
}, {
"name": "Transition",
"test": "someColor",
"size": 9201
}, {
"name": "Transitioner",
"test": "someColor",
"size": 19975
}, {
"name": "TransitionEvent",
"test": "someColor",
"size": 1116
}, {
"name": "Tween",
"test": "someColor",
"size": 6006
}]
}, {
"name": "data",
"test": "someColor",
"size": 4322
}]
} ;
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
d3.select(self.frameElement).style("height", "800px");
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 180; });
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes 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);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// 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);
}
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
First, you can change the color of the lines (links) just using a simple CSS hover, like so:
.link:hover {
stroke:blue;
}
This will turn the links blue on mouse over or hover.
Second, adding tooltips is slightly more complicated. One way is to have a hidden <div> on your page that becomes visible and moves to the <text> you are mousing over. It will then be hidden when you mouse out. To do so, add the following:
nodeEnter.on("mouseover", function (d) {
var r = d3.select(this).node().getBoundingClientRect();
d3.select("div#tooltip")
.style("display", "inline")
.style("top", (r.top-25) + "px")
.style("left", r.left + "px")
.style("position", "absolute")
.text(d.test);
})
.on("mouseout", function(){
d3.select("div#tooltip").style("display", "none")
});
This requires you to add the <div id="tooltip" style="display:none"></div> to your HTML page. To make the tooltip look slightly more tooltip-y, use the following CSS (I'm sure you can Google around and get an even better style):
div#tooltip{
color:#ffffff;
background:#000000;
opacity:1;
padding:5px;
}
I compiled this example in this fiddle.