How can i split the text into two parts in d3.js - d3.js

I want to put the name from the tree data to the left and right of the circle, separating it after the first comma. I'm new here, sorry for mistakes.
Normally it looks like this
This is how I want it to look
nodeEnter.append("text")
.attr("x", function(d) {
return d.children || d._children ? -10 : 10;
})
.attr("dy", ".15em")
.attr('class', 'nodeText')
.attr("text-anchor", function(d) {
return d.children || d._children ? "end" : "start";
})
.text(function(d) {
return d.name;
}).on("mousedown", function(){
d3.event.stopPropagation();
})
.style("fill-opacity", 0);
Sample Data
*let treeDatas = JSON.parse('[
{
"name": "gameplay_duration_total > 2151.38, notsubs: 56%, Amount: 2828",
"children": [
{
"name": "gameplay_duration_total > 6320.81, subs: 60%, Amount: 862",
"children": [
{
"name": "os_name_ios > 0.5, subs: 75%, Amount: 256",
"children": [
{
"name": "game_end__game_coloring__EC_S > 0.15, subs: 78%, Amount: 236",
"children": [
{
"name": "gameplay__game_our_emotions__duration_total_S > 14.35, subs: 84%, Amount: 165",
"children": [
{
"name": "subs: 98%, Amount: 46"
},
{
"name": "subs: 78%, Amount: 119"
}
]
},*

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>

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>

JSON instead of CSV for bubble chart

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"
}]

Modify lines/tooltip on hover

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.

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