JSON instead of CSV for bubble chart - d3.js

I'm using bubble chart which takes input from csv file, is there a way to use JSON instead?
Here is the Problem url:
http://ec2-54-198-148-171.compute-1.amazonaws.com/webapp/provider-view
Problem Code:
d3.csv(flare.csv, function(d) {
//console.log(d);
d.value = +d.value;
d.seq = +d.seq;
if (d.value) return d;
}, function(error, classes) {
if (error) throw error;
var root = d3.hierarchy({children: classes})
.sum(function(d) { return d.value; })
.each(function(d) {
if (id = d.data.id) {
var id,seq, i = id.lastIndexOf(".");
d.id = id;//console.log(i + " " + id);
d.package = id.slice(0, i);//console.log(d.package);
d.class = id.slice(i + 1);
d.seq = d.data.seq;
}
});
var node = svg.selectAll(".node")
.data(pack(root).leaves())
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
if(d.seq==1){
d.x = d.x - 100;
d.y = d.y + 20;
return "translate(" + d.x + "," + d.y + ")";
}else{
d.x = d.x + 500;
d.y = d.y + 20;
return "translate(" + d.x + "," + d.y + ")";
} });
node.append("circle")
.attr("id", function(d) { return d.id; })
.attr("r", function(d) { d.r = parseInt(d.r)-5; return d.r; })
.attr("onclick",function(d) { return "demo('" +d.id + "',"+ d.seq+","+ (d.x+d.r+111)+","+ (d.y+100-30)+");"; })
.style("fill", function(d) { //console.log(d.seq);
if(d.seq==1){
return "url(#gradient1)";
}else{
return "#773F9B";
}
});
node.append("clipPath")
.attr("id", function(d) { return "clip-" + d.id; })
.append("use")
.attr("xlink:href", function(d) { return "#" + d.id; });
node.append("div")
.attr("id","tooltip")
.attr("style","width:100px;height:10px;background-color:gray;z-index:1000");
});
Sample csv :
id,value,seq
demo11,100,1
demo12,200,1
demo13,300,1
demo14,400,1
demo15,500,1
demo16,600,1
demo17,600,1
demo21,50,2
demo22,100,2
demo23,150,2
demo24,200,2
demo25,250,2
demo26,300,2
demo27,350,2

The short answer is: yes.
The long answer: to change the data from a csv file to a json file, it's not simply a matter of changing d3.csv for d3.json. That's necessary, of course, as #RobertLongson said in the comments. But, besides that, you'll have to understand how d3.csv creates an array of objects with your CSV, since you need to create your JSON mimicking that array.
So, given your CSV, this is how d3.csv creates an array of objects:
var data = d3.csvParse(d3.select("#csv").text());
console.log(JSON.stringify(data))
pre {
display: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="csv">id,value,seq
demo11,100,1
demo12,200,1
demo13,300,1
demo14,400,1
demo15,500,1
demo16,600,1
demo17,600,1
demo21,50,2
demo22,100,2
demo23,150,2
demo24,200,2
demo25,250,2
demo26,300,2
demo27,350,2</pre>
That being said, to change your data from CSV to JSON (without doing any further change in the code), your JSON need to have exactly this structure:
[{
"id": "demo11",
"value": "100",
"seq": "1"
}, {
"id": "demo12",
"value": "200",
"seq": "1"
}, {
"id": "demo13",
"value": "300",
"seq": "1"
}, {
"id": "demo14",
"value": "400",
"seq": "1"
}, {
"id": "demo15",
"value": "500",
"seq": "1"
}, {
"id": "demo16",
"value": "600",
"seq": "1"
}, {
"id": "demo17",
"value": "600",
"seq": "1"
}, {
"id": "demo21",
"value": "50",
"seq": "2"
}, {
"id": "demo22",
"value": "100",
"seq": "2"
}, {
"id": "demo23",
"value": "150",
"seq": "2"
}, {
"id": "demo24",
"value": "200",
"seq": "2"
}, {
"id": "demo25",
"value": "250",
"seq": "2"
}, {
"id": "demo26",
"value": "300",
"seq": "2"
}, {
"id": "demo27",
"value": "350",
"seq": "2"
}]

Related

Zooming d3js graph corresponding to nodes count

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>

Updating nodes and links with labels in d3 force directed network graph is not removing the nodes properly

I am trying to create a d3 force directed network graph where based on a given network I can update the network by modifying the links and nodes and re-update them in the svg.
I tweaked the code so that a g element can be created which enclose each node circle so that I can add a text inside that same g element.
But now the labels are working perfectly but when I transition from graph 3 to graph 1 by clicking button 3 first then clicking button 1, the links that are redundant (a->d, a->f) are removed perfectly but the nodes that are redundant (e and f) stays in the svg.
I could not figure out whether it was a wrong selection or do I need some tweaking in the tick() function?
Here is the code:
var height = 200;
var width = 200;
const graph = {
"nodes": [
{ "name": "a", "group": 1 },
{ "name": "b", "group": 2 },
{ "name": "c", "group": 3 },
{ "name": "d", "group": 4 }
],
"links": [
{ "source": "a", "target": "b", "value": 1 },
{ "source": "b", "target": "c", "value": 1 },
{ "source": "c", "target": "d", "value": 1 }
]
}
const graph2 = {
"nodes": [
{ "name": "a", "group": 1 },
{ "name": "b", "group": 2 },
{ "name": "c", "group": 3 },
{ "name": "d", "group": 4 }
],
"links": [
{ "source": "a", "target": "b", "value": 1 },
{ "source": "b", "target": "c", "value": 1 },
{ "source": "c", "target": "d", "value": 1 },
{ "source": "a", "target": "d", "value": 1 }
]
}
const graph3 = {
"nodes": [
{ "name": "a", "group": 1 },
{ "name": "b", "group": 2 },
{ "name": "c", "group": 3 },
{ "name": "d", "group": 4 },
{ "name": "e", "group": 4 },
{ "name": "f", "group": 4 }
],
"links": [
{ "source": "a", "target": "b", "value": 1 },
{ "source": "b", "target": "c", "value": 1 },
{ "source": "c", "target": "d", "value": 1 },
{ "source": "a", "target": "d", "value": 1 },
{ "source": "f", "target": "a", "value": 1 }
]
}
var simulation = d3.forceSimulation()
.force("ct", d3.forceCenter(height / 2, width / 2))
.force("link", d3.forceLink().id(function(d) { return d.name; })
.distance(50).strength(2))
.force("charge", d3.forceManyBody().strength(-240))
// use forceX and forceY instead to change the relative positioning
// .force("centering", d3.forceCenter(width/2, height/2))
.force("x", d3.forceX(width / 2))
.force("y", d3.forceY(height / 2))
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("g").attr("class", "links");
svg.append("g").attr("class", "nodes");
function start(graph) {
var linkElements = svg.select(".links").selectAll(".link").data(graph.links);
linkElements.enter().append("line").attr("class", "link");
linkElements.exit().remove();
var nodeElements = svg.select(".nodes").selectAll(".node")
.data(graph.nodes, function(d) { return d.name })
.enter().append("g")
.attr("class", "node");
var circles = nodeElements.append("circle")
.attr("r", 8);
var labels = nodeElements.append("text")
.text(function(d) { return d.name; })
.attr("x", 10)
.attr("y", 10);
nodeElements.exit().remove();
simulation.nodes(graph.nodes);
simulation.force("link").links(graph.links);
simulation.alphaTarget(0.1).restart();
}
function tick() {
var nodeElements = svg.select(".nodes").selectAll(".node");
var linkElements = svg.select(".links").selectAll(".link");
nodeElements.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
linkElements.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; });
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.1).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
start(graph);
document.getElementById('btn1').addEventListener('click', function() {
start(graph);
});
document.getElementById('btn2').addEventListener('click', function() {
start(graph2);
});
document.getElementById('btn3').addEventListener('click', function() {
start(graph3);
});
.link {
stroke: #000;
stroke-width: 1.5px;
}
.node {
stroke-width: 1.5px;
}
text {
font-family: sans-serif;
font-size: 10px;
fill: #000000;
}
<body>
<div>
<button id='btn1'>1</button>
<button id='btn2'>2</button>
<button id='btn3'>3</button>
</div>
</body>
<script src="https://d3js.org/d3.v5.min.js"></script>
Here is the jsfiddle version of the code: https://jsfiddle.net/syedarehaq/myd0h5w1/
In the provided code, variable nodeElements contains the enter selection, rather than the whole data binding selection.
var nodeElements = svg.select(".nodes").selectAll(".node")
.data(graph.nodes, function(d) { return d.name })
.enter().append("g")
.attr("class", "node");
nodeElements declaration should not contain the .enter bit - it should be just like linkSelection variable declaration:
var nodeElements = svg.select(".nodes").selectAll(".node")
.data(graph.nodes, function(d) { return d.name })
Then, in order to append the new circles and texts only to the entering g elements, adapt as follows:
var enterSelection = nodeElements.enter().append("g")
.attr("class", "node");
var circles = enterSelection.append("circle")
.attr("r", 8);
var labels = enterSelection.append("text")
.text(function(d) { return d.name; })
.attr("x", 10)
.attr("y", 10);
The exit function call is now working as expected.
Demo in the snippet below.
var height = 200;
var width = 200;
const graph = {
"nodes": [
{ "name": "a", "group": 1 },
{ "name": "b", "group": 2 },
{ "name": "c", "group": 3 },
{ "name": "d", "group": 4 }
],
"links": [
{ "source": "a", "target": "b", "value": 1 },
{ "source": "b", "target": "c", "value": 1 },
{ "source": "c", "target": "d", "value": 1 }
]
}
const graph2 = {
"nodes": [
{ "name": "a", "group": 1 },
{ "name": "b", "group": 2 },
{ "name": "c", "group": 3 },
{ "name": "d", "group": 4 }
],
"links": [
{ "source": "a", "target": "b", "value": 1 },
{ "source": "b", "target": "c", "value": 1 },
{ "source": "c", "target": "d", "value": 1 },
{ "source": "a", "target": "d", "value": 1 }
]
}
const graph3 = {
"nodes": [
{ "name": "a", "group": 1 },
{ "name": "b", "group": 2 },
{ "name": "c", "group": 3 },
{ "name": "d", "group": 4 },
{ "name": "e", "group": 4 },
{ "name": "f", "group": 4 }
],
"links": [
{ "source": "a", "target": "b", "value": 1 },
{ "source": "b", "target": "c", "value": 1 },
{ "source": "c", "target": "d", "value": 1 },
{ "source": "a", "target": "d", "value": 1 },
{ "source": "f", "target": "a", "value": 1 }
]
}
var simulation = d3.forceSimulation()
.force("ct", d3.forceCenter(height / 2, width / 2))
.force("link", d3.forceLink().id(function(d) { return d.name; })
.distance(50).strength(2))
.force("charge", d3.forceManyBody().strength(-240))
// use forceX and forceY instead to change the relative positioning
// .force("centering", d3.forceCenter(width/2, height/2))
.force("x", d3.forceX(width / 2))
.force("y", d3.forceY(height / 2))
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("g").attr("class", "links");
svg.append("g").attr("class", "nodes");
function start(graph) {
var linkElements = svg.select(".links").selectAll(".link").data(graph.links);
linkElements.enter().append("line").attr("class", "link");
linkElements.exit().remove();
var nodeElements = svg.select(".nodes").selectAll(".node")
.data(graph.nodes, function(d) { return d.name })
var enterSelection = nodeElements.enter().append("g")
.attr("class", "node");
var circles = enterSelection.append("circle")
.attr("r", 8);
var labels = enterSelection.append("text")
.text(function(d) { return d.name; })
.attr("x", 10)
.attr("y", 10);
nodeElements.exit().remove();
simulation.nodes(graph.nodes);
simulation.force("link").links(graph.links);
simulation.alphaTarget(0.1).restart();
}
function tick() {
var nodeElements = svg.select(".nodes").selectAll(".node");
var linkElements = svg.select(".links").selectAll(".link");
nodeElements.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
linkElements.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; });
}
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.1).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
start(graph);
document.getElementById('btn1').addEventListener('click', function() {
start(graph);
});
document.getElementById('btn2').addEventListener('click', function() {
start(graph2);
});
document.getElementById('btn3').addEventListener('click', function() {
start(graph3);
});
.link {
stroke: #000;
stroke-width: 1.5px;
}
.node {
stroke-width: 1.5px;
}
text {
font-family: sans-serif;
font-size: 10px;
fill: #000000;
}
<body>
<div>
<button id='btn1'>1</button>
<button id='btn2'>2</button>
<button id='btn3'>3</button>
</div>
</body>
<script src="https://d3js.org/d3.v5.min.js"></script>

Root element is not showing its children in sunburst

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>

How to add an extra level in a drill down pie chart?

I have a nicely working drill down chart using d3.js, but I would like to add one (or more) deeper levels.
I can see how there's a level 0 (starting state) and a level 1 (one click deeper), but I can't seem to figure out how to implement that to a level 2 state (two clicks down).
Can somebody show me how to do that? I've got this so far: https://jsfiddle.net/yLsg841u/5/
<script type="text/javascript">
var salesData;
var chartInnerDiv = '<div class="innerCont" style="overflow: auto;top:100px; left: 400px; height:91% ; Width:100% ;position: relative;overflow: hidden;"/>';
var truncLengh = 30;
$(document).ready(function () {
Plot();
});
function Plot() {
TransformChartData(chartData, chartOptions, 0);
BuildPie("chart", chartData, chartOptions, 0)
}
function BuildPie(id, chartData, options, level) {
var xVarName;
var divisionRatio = 2.5;
var legendoffset = (level == 0) ? 0 : -40;
d3.selectAll("#" + id + " .innerCont").remove();
$("#" + id).append(chartInnerDiv);
chart = d3.select("#" + id + " .innerCont");
var yVarName = options[0].yaxis;
width = $(chart[0]).outerWidth(),
height = $(chart[0]).outerHeight(),
radius = Math.min(width, height) / divisionRatio;
if (level == 1) {
xVarName = options[0].xaxisl1;
}
else {
xVarName = options[0].xaxis;
}
var rcolor = d3.scale.ordinal().range(runningColors);
arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - 200);
var arcOver = d3.svg.arc().outerRadius(radius + 20).innerRadius(radius - 180);
chart = chart
.append("svg") //append svg element inside #chart
.attr("width", width) //set width
.attr("height", height) //set height
.append("g")
.attr("transform", "translate(" + (width / divisionRatio) + "," + ((height / divisionRatio) + 30) + ")");
var pie = d3.layout.pie()
.sort(null)
.value(function (d) {
return d.Total;
});
var g = chart.selectAll(".arc")
.data(pie(runningData))
.enter().append("g")
.attr("class", "arc");
var count = 0;
var path = g.append("path")
.attr("d", arc)
.attr("id", function (d) { return "arc-" + (count++); })
.style("opacity", function (d) {
return d.data["op"];
});
path.on("mouseenter", function (d) {
d3.select(this)
.attr("stroke", "white")
.transition()
.duration(200)
.attr("d", arcOver)
.attr("stroke-width", 1);
})
.on("mouseleave", function (d) {
d3.select(this).transition()
.duration(200)
.attr("d", arc)
.attr("stroke", "none");
})
.on("click", function (d) {
if (this._listenToEvents) {
// Reset inmediatelly
d3.select(this).attr("transform", "translate(0,0)")
// Change level on click if no transition has started
path.each(function () {
this._listenToEvents = false;
});
}
d3.selectAll("#" + id + " svg").remove();
if (level == 1) {
TransformChartData(chartData, options, 0, d.data[xVarName]);
BuildPie(id, chartData, options, 0);
}
else {
var nonSortedChart = chartData.sort(function (a, b) {
return parseFloat(b[options[0].yaxis]) - parseFloat(a[options[0].yaxis]);
});
TransformChartData(nonSortedChart, options, 1, d.data[xVarName]);
BuildPie(id, nonSortedChart, options, 1);
}
});
path.append("svg:title")
.text(function (d) {
return d.data["title"] + " (" + d.data[yVarName] + ")";
});
path.style("fill", function (d) {
return rcolor(d.data[xVarName]);
})
.transition().duration(1000).attrTween("d", tweenIn).each("end", function () {
this._listenToEvents = true;
});
g.append("text")
.attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.style("opacity", 1)
.text(function (d) {
return d.data[yVarName];
});
count = 0;
var legend = chart.selectAll(".legend")
.data(runningData).enter()
.append("g").attr("class", "legend")
.attr("legend-id", function (d) {
return count++;
})
.attr("transform", function (d, i) {
return "translate(15," + (parseInt("-" + (runningData.length * 10)) + i * 28 + legendoffset) + ")";
})
.style("cursor", "pointer")
.on("click", function () {
var oarc = d3.select("#" + id + " #arc-" + $(this).attr("legend-id"));
oarc.style("opacity", 0.3)
.attr("stroke", "white")
.transition()
.duration(200)
.attr("d", arcOver)
.attr("stroke-width", 1);
setTimeout(function () {
oarc.style("opacity", function (d) {
return d.data["op"];
})
.attr("d", arc)
.transition()
.duration(200)
.attr("stroke", "none");
}, 1000);
});
var leg = legend.append("rect");
leg.attr("x", width / 2)
.attr("width", 18).attr("height", 18)
.style("fill", function (d) {
return rcolor(d[yVarName]);
})
.style("opacity", function (d) {
return d["op"];
});
legend.append("text").attr("x", (width / 2) - 5)
.attr("y", 9).attr("dy", ".35em")
.style("text-anchor", "end").text(function (d) {
return d.caption;
});
leg.append("svg:title")
.text(function (d) {
return d["title"] + " (" + d[yVarName] + ")";
});
function tweenOut(data) {
data.startAngle = data.endAngle = (2 * Math.PI);
var interpolation = d3.interpolate(this._current, data);
this._current = interpolation(0);
return function (t) {
return arc(interpolation(t));
};
}
function tweenIn(data) {
var interpolation = d3.interpolate({ startAngle: 0, endAngle: 0 }, data);
this._current = interpolation(0);
return function (t) {
return arc(interpolation(t));
};
}
}
function TransformChartData(chartData, opts, level, filter) {
var result = [];
var resultColors = [];
var counter = 0;
var hasMatch;
var xVarName;
var yVarName = opts[0].yaxis;
if (level == 1) {
xVarName = opts[0].xaxisl1;
for (var i in chartData) {
hasMatch = false;
for (var index = 0; index < result.length; ++index) {
var data = result[index];
if ((data[xVarName] == chartData[i][xVarName]) && (chartData[i][opts[0].xaxis]) == filter) {
result[index][yVarName] = result[index][yVarName] + chartData[i][yVarName];
hasMatch = true;
break;
}
}
if ((hasMatch == false) && ((chartData[i][opts[0].xaxis]) == filter)) {
if (result.length < 9) {
ditem = {}
ditem[xVarName] = chartData[i][xVarName];
ditem[yVarName] = chartData[i][yVarName];
ditem["caption"] = chartData[i][xVarName].substring(0, 10) + '...';
ditem["title"] = chartData[i][xVarName];
ditem["op"] = 1.0 - parseFloat("0." + (result.length));
result.push(ditem);
resultColors[counter] = opts[0].color[0][chartData[i][opts[0].xaxis]];
counter += 1;
}
}
}
}
else {
xVarName = opts[0].xaxis;
for (var i in chartData) {
hasMatch = false;
for (var index = 0; index < result.length; ++index) {
var data = result[index];
if (data[xVarName] == chartData[i][xVarName]) {
result[index][yVarName] = result[index][yVarName] + chartData[i][yVarName];
hasMatch = true;
break;
}
}
if (hasMatch == false) {
ditem = {};
ditem[xVarName] = chartData[i][xVarName];
ditem[yVarName] = chartData[i][yVarName];
ditem["caption"] = opts[0].captions != undefined ? opts[0].captions[0][chartData[i][xVarName]] : "";
ditem["title"] = opts[0].captions != undefined ? opts[0].captions[0][chartData[i][xVarName]] : "";
ditem["op"] = 1;
result.push(ditem);
resultColors[counter] = opts[0].color != undefined ? opts[0].color[0][chartData[i][xVarName]] : "";
counter += 1;
}
}
}
runningData = result;
runningColors = resultColors;
return;
}
chartOptions = [{
"captions": [{ "INDIA": "INDIA", "CANADA": "CANADA", "USA": "USA" }],
"color": [{ "INDIA": "#FFA500", "CANADA": "#0070C0", "USA": "#ff0000" }],
"xaxis": "Country",
"xaxisl1": "Model",
"yaxis": "Total"
}]
var chartData = [
{
"Country": "USA",
"Model": "Model 1",
"Total": 487
},
{
"Country": "USA",
"Model": "Model 2",
"Total": 185
},
{
"Country": "USA",
"Model": "Model 3",
"Total": 140
},
{
"Country": "USA",
"Model": "Model 4",
"Total": 108
},
{
"Country": "USA",
"Model": "Model 5",
"Total": 26
},
{
"Country": "USA",
"Model": "Model 6",
"Total": 106
},
{
"Country": "USA",
"Model": "Model 7",
"Total": 27
},
{
"Country": "USA",
"Model": "Model 8",
"Total": 44
},
{
"Country": "USA",
"Model": "Model 9",
"Total": 96
},
{
"Country": "INDIA",
"Model": "Model 1",
"Total": 411
},
{
"Country": "INDIA",
"Model": "Model 2",
"Total": 33
},
{
"Country": "INDIA",
"Model": "Model 3",
"Total": 32
},
{
"Country": "INDIA",
"Model": "Model 4",
"Total": 29
},
{
"Country": "INDIA",
"Model": "Model 5",
"Total": 29
},
{
"Country": "CANADA",
"Model": "Model 1",
"Total": 7
},
{
"Country": "CANADA",
"Model": "Model 2",
"Total": 20
},
{
"Country": "CANADA",
"Model": "Model 3",
"Total": 232
},
{
"Country": "CANADA",
"Model": "Model 4",
"Total": 117
}
];
I have tried adding one level.
Firstly, make sure you have json data for other level
Secondly, mention the 2nd level name in chartOptions as "xaxisl2":"YourLevelName"
Finally, add else if statement for (level==2) as follows:
TransformChartData(nonSortedChart, options, 2, d.data[xVarName]);
BuildPie(id, nonSortedChart, options, 2);
where xVarName=opts[0].xaxisl2;

Json d3 access each object

{
"name": "Max",
"value": 107,
"children": [
{
"name": "Don",
"value": 60,
"children" [
{"name": "CC", "value": 25},
{"name": "Jim", "value": 35}
]
},
{
"name": "David",
"value": 47,
"children": [
{"name": "Jeff", "value": 32},
{"name": "Buffy", "value": 15}
]
}
]
}
How can I access the inner most child name with d3?
I tried doing :
.text(function (d) { return d.children ? null : d.name; });
But it didn't work....
When I do
.text(function (d) { return d.name });
it only shows the name of the outer loop --> Don, David.
d3.json('flare.json', function (data) {
var canvas = d3.select('p1')
.append('svg')
.attr('width', 800)
.attr('height', 800)
var color = d3.scale.category20c();
var data1 = data.children;
canvas.selectAll('text')
.data(data1)
.enter()
.append('text')
.attr('x', function (d) { return 2; })
.attr('y', function (d, i) { return i * 15; })
.attr('fill', 'black')
.style('font-size', '12px')
.text(function (d) { return d.children ? null: d.name; })
Data I had before ↓ ↓
{
"name": "Don",
"value": 75,
"children" [
{"name": "CC", "value": 25},
{"name": "Jim", "value": 35}
]
}
When the data was in this single nested format, my code worked perfectly, but when I did double nest on it, it no longer works
You need a recursive function for this --
function getNames(d) {
return d.children ? d.children.map(getNames) : d.name;
}
This will return a nested list with the names of the elements that have no children.

Resources