d3 force links not connecting - javascript
I'm trying to create a force-directed layout d3 viz, and while the nodes are rendering fine I'm struggling with the link connections, which don't seem to register at all.
I've done some digging around but I'm struggling to resolve this, can anyone help?
Codepen - https://codepen.io/quirkules/pen/dqXRwj
var links_data = [{"source":"JRASERVER","target":"BAM","count":4},{"source":"JRASERVER","target":"BON","count":2},{"source":"JRASERVER","target":"BSERV","count":4},{"source":"JRASERVER","target":"CLOUD","count":3},{"source":"JRASERVER","target":"CONFCLOUD","count":1},{"source":"JRASERVER","target":"CONFSERVER","count":31},{"source":"JRASERVER","target":"CWD","count":13},{"source":"JRASERVER","target":"FE","count":7},{"source":"JRASERVER","target":"HCPUB","count":1},{"source":"JRASERVER","target":"ID","count":1},{"source":"JRASERVER","target":"JPOSERVER","count":2},{"source":"JRASERVER","target":"JRACLOUD","count":41},{"source":"JRASERVER","target":"JSDCLOUD","count":2},{"source":"JRASERVER","target":"JSDSERVER","count":23},{"source":"JRASERVER","target":"JSWCLOUD","count":3},{"source":"JRASERVER","target":"JSWSERVER","count":40},{"source":"JRASERVER","target":"TRANS","count":2}];
var nodes_data = [{"name":"JRASERVER","total":4}, {"name":"BAM","total":4},{"name":"BON","total":2},{"name":"BSERV","total":4},{"name":"CLOUD","total":3},{"name":"CONFCLOUD","total":1},{"name":"CONFSERVER","total":31},{"name":"CWD","total":13},{"name":"FE","total":7},{"name":"HCPUB","total":1},{"name":"ID","total":1},{"name":"JPOSERVER","total":2},{"name":"JRACLOUD","total":41},{"name":"JSDCLOUD","total":2},{"name":"JSDSERVER","total":23},{"name":"JSWCLOUD","total":3},{"name":"JSWSERVER","total":40},{"name":"TRANS","total":2}];
//create somewhere to put the force directed graph
var height = 650,
width = 950;
var svg = d3.select("body").append("svg")
.attr('width',width)
.attr('height',height);
var radius = 15;
//set up the simulation and add forces
var simulation = d3.forceSimulation()
.nodes(nodes_data);
var link_force = d3.forceLink()
.id(function(d) { return d.name; })
;
var charge_force = d3.forceManyBody()
.strength(-100);
var center_force = d3.forceCenter(width / 2, height / 2);
simulation
.force("charge_force", charge_force)
.force("center_force", center_force)
.force("link",link_force)
;
//add tick instructions:
simulation.on("tick", tickActions );
//add encompassing group for the zoom
var g = svg.append("g")
.attr("class", "everything");
//draw circles for the nodes
var node = g.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes_data)
.enter()
.append("circle")
.attr("r", radius)
.attr("fill", "#FFFFFF")
.on("mouseover", mouseOver(.1))
.on("mouseout", mouseOut);
// add the curved links to our graphic
var link = g.selectAll(".link")
.data(links_data)
.enter()
.append("path")
.attr("class", "link")
.style('stroke', "#FF00FF")
.attr('stroke-width', 2);
//add drag capabilities
var drag_handler = d3.drag()
.on("start", drag_start)
.on("drag", drag_drag)
.on("end", drag_end);
drag_handler(node);
//add zoom capabilities
var zoom_handler = d3.zoom()
.on("zoom", zoom_actions);
zoom_handler(svg);
/** Functions **/
//Drag functions
//d is the node
function drag_start(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
//make sure you can't drag the circle outside the box
function drag_drag(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function drag_end(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
//Zoom functions
function zoom_actions(){
g.attr("transform", d3.event.transform)
}
function tickActions() {
//update circle positions each tick of the simulation
node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
//update link positions
link.attr("d", positionLink);
}
// links are drawn as curved paths between nodes,
// through the intermediate nodes
function positionLink(d) {
var offset = 30;
var midpoint_x = (d.source.x + d.target.x) / 2;
var midpoint_y = (d.source.y + d.target.y) / 2;
var dx = (d.target.x - d.source.x);
var dy = (d.target.y - d.source.y);
var normalise = Math.sqrt((dx * dx) + (dy * dy));
var offSetX = midpoint_x + offset * (dy / normalise);
var offSetY = midpoint_y - offset * (dx / normalise);
return "M" + d.source.x + "," + d.source.y +
"S" + offSetX + "," + offSetY +
" " + d.target.x + "," + d.target.y;
}
// build a dictionary of nodes that are linked
var linkedByIndex = {};
links_data.forEach(function(d) {
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
// check the dictionary to see if nodes are linked
function isConnected(a, b) {
return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index] || a.index == b.index;
}
// fade nodes on hover
function mouseOver(opacity) {
return function(d) {
// check all other nodes to see if they're connected
// to this one. if so, keep the opacity at 1, otherwise
// fade
node.style("stroke-opacity", function(o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
return thisOpacity;
});
node.style("fill-opacity", function(o) {
thisOpacity = isConnected(d, o) ? 1 : opacity;
return thisOpacity;
});
// also style link accordingly
link.style("stroke-opacity", function(o) {
return o.source === d || o.target === d ? 1 : opacity;
});
link.style("stroke", function(o) {
return o.source === d || o.target === d ? "#FF0000" : "#ddd";
});
};
}
function mouseOut() {
node.style("stroke-opacity", 1);
node.style("fill-opacity", 1);
link.style("stroke-opacity", 1);
link.style("stroke", "#00FF00");
}
You have to supply the link records to the link force.
var link_force = d3.forceLink(links_data)
.id(function(d) { return d.name; })
;
Have a look at your CSS
.link {
fill: #FFFFFF00;
}
Better is
.link {
fill: none;
}
Related
How to remove the default "left" position of node. d3.js
I have a problem where the node always move left. Here is my code: <div id="tree-container"></div> <script src="<?php echo base_url('d3js-nettree/js/d3.js');?>" type="text/javascript"></script> <script> <?php if(isset($params['user_code'])){ ?> treeJSON = d3.json("<?php echo base_url('d3js-parse/'.$params['user_code'].'.json');?>", function(error, treeData) { // Calculate total nodes, max label length var totalNodes = 0; var maxLabelLength = 0; // Misc. variables var zoomFactor = 1; var i = 0; var duration = 750; var root; var rectWidth = 160, rectHeight = 125; // size of the diagram var viewerWidth = $("#tree-container").width(); var viewerHeight = 500; var tree = d3.layout.tree() .size([viewerWidth, viewerHeight]); // define a d3 diagonal projection for use by the node paths later on. var diagonal = d3.svg.diagonal() .projection(function(d) { return [d.x, d.y]; }); // A recursive helper function for performing some setup by walking through all nodes function visit(parent, visitFn, childrenFn) { if (!parent) return; visitFn(parent); var children = childrenFn(parent); if (children) { var count = children.length; for (var i = 0; i < count; i++) { visit(children[i], visitFn, childrenFn); } } } // Define the zoom function for the zoomable tree function zoom() { svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); } // define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents var zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]).on("zoom", zoom); d3.selectAll('button').on('click', function(){ if(this.id === 'zoom_in') { zoomFactor = zoomFactor + 0.2; zoomListener.scale(zoomFactor).event(d3.select("#tree-container")); } else if(this.id === 'zoom_out') { zoomFactor = zoomFactor - 0.2; zoomListener.scale(zoomFactor).event(d3.select("#tree-container")); } else if(this.id === 'up_level') { updateNewTree("ID04838614"); } }); // define the baseSvg, attaching a class for styling and the zoomListener var baseSvg = d3.select("#tree-container").append("svg") .attr("width", viewerWidth) .attr("height", viewerHeight) .attr("class", "overlay") .call(zoomListener); // Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children. function centerNode(source) { scale = zoomListener.scale(); x = -source.x0; y = -source.y0; x = x * scale + viewerWidth / 2; y = y * scale + viewerHeight / 2; d3.select('g').transition() .duration(duration) .attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")"); zoomListener.scale(scale); zoomListener.translate([x, y]); } // Call visit function to establish maxLabelLength visit(treeData, function(d) { totalNodes++; maxLabelLength = Math.max(d.distributor_code.length, maxLabelLength); }, function(d) { return d.children && d.children.length > 0 ? d.children : null; }); // define click event function click(d) { console.log("clicked"); // if (d3.event.defaultPrevented) return; // click suppressed //d = toggleChildren(d); if(d.url !== "") { window.open(d.url, "_self"); } else { updateNewTree(d.distributor_code); } update(d); centerNode(d); } function update(source) { // Compute the new height, function counts total children of root node and sets tree height accordingly. // This prevents the layout looking squashed when new nodes are made visible or looking sparse when nodes are removed // This makes the layout more consistent. 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, root); var newWidth = d3.max(levelWidth) * 300; // 300 pixels per line tree = tree.size([newWidth, viewerHeight]); // Compute the new tree layout. var nodes = tree.nodes(root).reverse(), links = tree.links(nodes); // Set widths between levels based on maxLabelLength. nodes.forEach(function(d) { //d.y = (d.depth * (maxLabelLength * 10)); //maxLabelLength * 10px // alternatively to keep a fixed scale one can set a fixed depth per level // Normalize for fixed-depth by commenting out below line d.y = (d.depth * 200); //200px per level. }); // Update the nodes… node = svgGroup.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.x0 + "," + source.y0 + ")"; }) .on('click', click); nodeEnter.append("image") .attr("href", "<?php echo base_url('assets/images/people.png');?>") .attr("x", -rectWidth/4) .attr("y", -rectHeight-75) .attr("width", 75) .attr("height", 75); nodeEnter.append("rect") .attr('class', 'nodeRect') .attr("x", -rectWidth/2) .attr("y", -rectHeight) .attr("rx", 10) .attr("ry", 10) .attr("width", rectWidth) .attr("height", rectHeight) .style("fill", function(d) { //return d._children ? "lightsteelblue" : "#fff"; }); nodeEnter.append("text") .attr('class', 'txt1') .attr("x", 0) .attr("y", -rectHeight+15) .attr('class', 'textBold') .attr("text-anchor", "middle") .text(function(d) { if(d.distributor_code === "") return ""; else return d.user_code; }); nodeEnter.append("text") .attr('class', 'txt2') .attr("x", 0) .attr("y", -rectHeight+25) .attr("text-anchor", "middle") .text(function(d) { if(d.distributor_code === "") return ""; else return d.fullname; }); //IT GOES ON FOR SEVERAL MORE // Transition nodes to their new position. var nodeUpdate = node.transition() .duration(duration) .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); // Fade the text in 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.x + "," + source.y + ")"; }) .remove(); nodeExit.select("rect") .attr("width", 0) .attr("height", 0); nodeExit.select("text") .style("fill-opacity", 0); nodeExit.select("image") .style("display", "none"); // Update the links… var link = svgGroup.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; }); } function updateNewTree($base_id) { // Get the data again d3.json("nettree-alt.json", function(error, treeData) { // Call visit function to establish maxLabelLength visit(treeData, function(d) { totalNodes++; maxLabelLength = Math.max(d.distributor_code.length, maxLabelLength); }, function(d) { return d.children && d.children.length > 0 ? d.children : null; }); root = treeData; root.x0 = viewerHeight / 2; root.y0 = 0; // Layout the tree initially and center on the root node. update(root); centerNode(root); }); } // Append a group which holds all nodes and which the zoom Listener can act upon. var svgGroup = baseSvg.append("g"); // Define the root root = treeData; root.x0 = viewerHeight / 2; root.y0 = -100; // Layout the tree initially and center on the root node. update(root); centerNode(root); }); <?php } ?> function EnableTreeMode(){ $('.tree').treegrid({ expanderExpandedClass: 'glyphicon glyphicon-minus', expanderCollapsedClass: 'glyphicon glyphicon-plus' }); $('.tree').treegrid('collapseAll'); } EnableTreeMode(); function collapse(){ $('.tree').treegrid('collapseAll'); } function expand(){ $('.tree').treegrid('expandAll'); } </script> The problem is like this, i have a "tree" that consist of users which pulls data from a json file: USER 1 /\ USER 2 USER 3 What i was expecting when i remove a user, say user 2, the "tree" should be like this: USER 1 /\ NONE USER 3 But instead the result i got were like this: USER 1 /\ USER 3 NONE After i deleted USER 2 the USER 3, which is on the right node, moved on the left node. I have tried debugging my code line by line but still no result. TIA.
D3-Chord: Flowing circle elements on chord-path mouseover
I am trying to implement an animation effect using svg circle elements on the mouse-over event of a chord path in D3 chord diagram. The inspiration for this trial is the following implementation of a sankey diagram: https://bl.ocks.org/micahstubbs/ed0ae1c70256849dab3e35a0241389c9 I have managed to insert the circle elements on the mouse-over event for the chords. However, I am having difficulty in figuring out how to make them follow the path of the chord. (Line 69-106 in the following JS code). My JS code (chord.js) //******************************************************************* // CREATE MATRIX AND MAP //******************************************************************* var matrix, mmap, rdr; d3.csv('data/out.csv', function(error, data) { var mpr = chordMpr(data); mpr.addValuesToMap('Source') .setFilter(function(row, a, b) { return (row.Source === a.name && row.Destination === b.name) }) .setAccessor(function(recs, a, b) { if (!recs[0]) return 0; return +recs[0].Count; }); matrix = mpr.getMatrix(); mmap = mpr.getMap(); rdr = chordRdr(matrix, mmap); drawChords(); }); //******************************************************************* // DRAW THE CHORD DIAGRAM //******************************************************************* function drawChords() { var w = window.innerWidth || document.body.clientWidth, h = 700, r1 = h / 2, r0 = r1 - 150; var svg = d3.select("body").append("svg:svg") .attr("width", w) .attr("height", h) .append("svg:g") .attr("id", "circle") .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")"); var chord = d3.layout.chord() .padding(.15) .sortChords(d3.descending); chord.matrix(matrix); var arc = d3.svg.arc() .innerRadius(r0*1.03) .outerRadius(r0*1.03 + 20); var path = d3.svg.chord() .radius(r0); var g = svg.selectAll("g.group") .data(chord.groups()) .enter() .append("g") .attr("class", "group"); var paths = g.append("svg:path") .style("stroke", function(d) { return fillcolor(rdr(d).gname); }) .style("fill", function(d) { return fillcolor(rdr(d).gname); }) .attr("d", arc) .attr("class", "arcs"); var chordPaths = svg.selectAll("path.chord") .data(chord.chords()) .enter().append("svg:path") .attr("class", "chord") .on("mouseover", function(d) { //context = d3.select('canvas').node().getContext('2d'); //context.clearRect(0, 0, 1000, 1000); //context.fillStyle = 'gray'; //context.lineWidth = '1px'; currentTime = 500; current = currentTime * 0.15 * (0.5 + (Math.random())); currentPos = this.getPointAtLength(current); //context.beginPath(); //context.fillStyle = "black"; /*context.arc( Math.abs(currentPos.x), Math.abs(currentPos.y), 2, 0, 2 * Math.PI ); context.fill();*/ currentpath = this; svg.insert("circle") .attr("cx",currentPos.x) .attr("cy",currentPos.y) .attr("r",2) .style("stroke-opacity", 1) .style("fill", this.style.fill) .transition() .duration(1000) .ease(Math.sqrt) .attr("cx",function(){ currentPos = currentpath.getPointAtLength(current+100); return currentPos.x; }) .attr("cy",function(){ currentPos = currentpath.getPointAtLength(current-100); return currentPos.y; }) .remove(); }) .style("fill", function(d) { return fillcolor(rdr(d.target).gname); }) .attr("d", path); } function fillcolor(segmentvalue){ if (segmentvalue.includes("Segment A")) { return '#ff3a21' } else if (segmentvalue.includes("Segment C")) { return '#26bde2' } else if (segmentvalue.includes("Segment D")) { return '#fcc30b' } else if (segmentvalue.includes("Segment B")) { return '#dd1367' } else if (segmentvalue.includes("Segment E")) { return '#a1e972' } else { return '#72e8a4' } } Here is the HTML: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> #circle circle { fill: none; pointer-events: all; } path.chord { fill-opacity: .6; stroke: #000; stroke-width: .25px; } </style> </head> <body> <script src="d3/d3.js"></script> <script src="d3/underscore.js"></script> <script type="text/javascript" src="d3/gistfile1.js"></script> <script type="text/javascript" src="js/chord.js"></script> </body> </html> Here is my data file (out.csv): Source,Destination,Count, Segment A,Segment A,597.7731179, Segment B,Segment A,428.4797097, Segment C,Segment A,242.5536698, Segment D,Segment A,39.18270781, Segment F,Segment A,373.4118141, Segment E,Segment A,342.1175938, Segment B,Segment B,695.841404, Segment C,Segment B,586.8204889, Segment D,Segment B,519.0497198, Segment F,Segment B,142.271554, Segment E,Segment B,282.7048795, Segment A,Segment B,552.8162888, Segment C,Segment C,162.7852664, Segment D,Segment C,150.6887517, Segment F,Segment C,631.6468679, Segment E,Segment C,611.0627425, Segment A,Segment C,344.1286204, Segment B,Segment C,395.710855, Segment D,Segment D,141.5878005, Segment F,Segment D,254.2566994, Segment E,Segment D,483.4672747, Segment A,Segment D,5.942896921, Segment B,Segment D,185.6991357, Segment C,Segment D,138.2424522, I have implemented a close enough solution and hosted it at: https://jsfiddle.net/Edwig_Noronha/fb9j5v4t/
//******************************************************************* // CREATE MATRIX AND MAP //******************************************************************* var matrix, mmap, rdr; d3.csv('data/out.csv', function(error, data) { var mpr = chordMpr(data); mpr .addValuesToMap('Source') .setFilter(function(row, a, b) { return (row.Source === a.name && row.Destination === b.name) }) .setAccessor(function(recs, a, b) { if (!recs[0]) return 0; return +recs[0].Count; }); matrix = mpr.getMatrix(); mmap = mpr.getMap(); rdr = chordRdr(matrix, mmap); drawChords(); }); //******************************************************************* // DRAW THE CHORD DIAGRAM //******************************************************************* function drawChords() { var w = window.innerWidth || document.body.clientWidth, h = 700, r1 = h / 2, r0 = r1 - 150; var svg = d3.select("body").append("svg:svg") .attr("width", w) .attr("height", h) .append("svg:g") .attr("id", "circle") .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")"); var chord = d3.layout.chord() .padding(.15) .sortChords(d3.descending); chord.matrix(matrix); var arc = d3.svg.arc() .innerRadius(r0*1.03) .outerRadius(r0*1.03 + 20); var path = d3.svg.chord() .radius(r0); var g = svg.selectAll("g.group") .data(chord.groups()) .enter() .append("g") .attr("class", "group"); var paths = g.append("svg:path") .style("stroke", function(d) { return fillcolor(rdr(d).gname); }) .style("fill", function(d) { return fillcolor(rdr(d).gname); }) .attr("d", arc) .attr("class", "arcs"); var chordPaths = svg.selectAll("path.chord") .data(chord.chords(),function(d,i){return i;}) .enter().append("svg:path") .attr("class", "chord") .attr("id", function(d,i){return "chord"+i}) .on("mouseover", function(d,i) { this.classList.add("hovered"); currentpath = this; startPoint = pathStartPoint(currentpath); function loop(thispath) { if (!thispath.classList.contains("hovered")) return; setTimeout(function () { particle = svg.insert("circle") .attr("class",function(){return currentpath.getAttribute("id")+"-circle"}) .attr("r",2) .style("stroke-opacity", 1) .style("fill", currentpath.style.fill) .attr("transform", "translate(" + startPoint[0] + "," + startPoint[1] + ")") .transition() .duration(2000) .attrTween("transform", translateAlong(currentpath)) .remove(); loop(thispath); }, 300); } loop(this); }) .on("mouseout",function(d,i){ this.classList.remove("hovered"); }) .style("fill", function(d) { return fillcolor(rdr(d.target).gname); }) .attr("d", path); } //Get path start point for placing marker function pathStartPoint(path) { var d = path.getAttribute("d"); var dsplitted = d.split(" "); return dsplitted[1].split(","); }; function translateAlong(path) { var l = path.getTotalLength(); var t0 = 0; return function(i) { return function(t) { var p0 = path.getPointAtLength(t0 * l);//previous point var p = path.getPointAtLength(t * l);////current point t0 = t; var centerX = p.x, centerY = p.y; return "translate(" + centerX + "," + centerY + ")"//rotate(" + angle + " 24" + " 12" +")"; } } } function fillcolor(segmentvalue){ if (segmentvalue.includes("Segment A")) { return '#ff3a21' } else if (segmentvalue.includes("Segment C")) { return '#26bde2' } else if (segmentvalue.includes("Segment D")) { return '#fcc30b' } else if (segmentvalue.includes("Segment B")) { return '#dd1367' } else if (segmentvalue.includes("Segment E")) { return '#a1e972' } else { return '#72e8a4' } } The above changes in the chord.js file implement a close enough transition. The working code is hosted at: https://jsfiddle.net/Edwig_Noronha/fb9j5v4t/
d3 v4 add arrows to force-directed graph
I'm trying to create a force-directed graph in d3.js with arrows pointing to non-uniform sized nodes. I came across this example here but for the life of me I can't adapt my code to add the arrows in. I'm not sure if I need to be adding something extra to the tick function, or if I'm referencing something incorrectly. Can anyone help me out? Codepen - https://codepen.io/quirkules/pen/dqXRwj var links_data = [{"source":"ABS","target":"ABS","count":8},{"source":"ABS","target":"ATS","count":1},{"source":"ABS","target":"CR","count":8},{"source":"ABS","target":"ENV","count":1},{"source":"ABS","target":"INT","count":16},{"source":"ABS","target":"ITS","count":9},{"source":"ABS","target":"PDG","count":1},{"source":"ABS","target":"PER","count":4},{"source":"ABS","target":"PRAC","count":3},{"source":"AC","target":"AC","count":1},{"source":"AC","target":"INT","count":9},{"source":"AC","target":"ITS","count":1},{"source":"ACDC","target":"ACDC","count":1},{"source":"ACDC","target":"CR","count":2},{"source":"ACDC","target":"ITS","count":13},{"source":"ACDC","target":"PER","count":4},{"source":"APL","target":"APL","count":8},{"source":"APL","target":"CR","count":3},{"source":"APL","target":"ENV","count":1},{"source":"APL","target":"INT","count":1},{"source":"APL","target":"ITS","count":29},{"source":"APL","target":"LA","count":1},{"source":"APL","target":"PEG","count":1},{"source":"APL","target":"PER","count":3},{"source":"AST","target":"AST","count":17},{"source":"AST","target":"COP","count":1},{"source":"AST","target":"DBT","count":2},{"source":"AST","target":"DEVOPS","count":1},{"source":"AST","target":"IGN","count":1},{"source":"AST","target":"INT","count":2},{"source":"AST","target":"ITS","count":32},{"source":"AST","target":"PDG","count":2},{"source":"AST","target":"PER","count":8},{"source":"ATS","target":"ABS","count":1},{"source":"ATS","target":"ATS","count":21},{"source":"ATS","target":"DBT","count":1},{"source":"ATS","target":"INT","count":3},{"source":"ATS","target":"PDG","count":1},{"source":"ATS","target":"PEG","count":1},{"source":"CAR","target":"APL","count":1},{"source":"CAR","target":"CAR","count":9},{"source":"CAR","target":"COP","count":1},{"source":"CAR","target":"INT","count":9},{"source":"CAR","target":"ITS","count":8},{"source":"IGN","target":"CR","count":4},{"source":"IGN","target":"IGN","count":13},{"source":"IGN","target":"INT","count":5},{"source":"IGN","target":"ITS","count":13},{"source":"IGN","target":"PER","count":4},{"source":"IGN","target":"PRAC","count":1},{"source":"LA","target":"AC","count":1},{"source":"LA","target":"INT","count":1},{"source":"LA","target":"ITS","count":37},{"source":"LA","target":"LA","count":18},{"source":"LA","target":"PER","count":2},{"source":"LOT","target":"LOT","count":18},{"source":"PDG","target":"ABS","count":1},{"source":"PDG","target":"AST","count":4},{"source":"PDG","target":"ATS","count":1},{"source":"PDG","target":"CAR","count":1},{"source":"PDG","target":"CR","count":8},{"source":"PDG","target":"ICS","count":1},{"source":"PDG","target":"IGN","count":3},{"source":"PDG","target":"INT","count":18},{"source":"PDG","target":"ITS","count":6},{"source":"PDG","target":"NRB","count":4},{"source":"PDG","target":"ONT","count":1},{"source":"PDG","target":"PDG","count":24},{"source":"PDG","target":"PER","count":1},{"source":"PEG","target":"CAR","count":1},{"source":"PEG","target":"ENV","count":1},{"source":"PEG","target":"INFRA","count":1},{"source":"PEG","target":"ITS","count":22},{"source":"PEG","target":"LA","count":1},{"source":"PEG","target":"PEG","count":51},{"source":"PEG","target":"PER","count":6},{"source":"RPT","target":"ABS","count":1},{"source":"RPT","target":"APL","count":1},{"source":"RPT","target":"IGN","count":1},{"source":"RPT","target":"INT","count":9},{"source":"RPT","target":"ITS","count":2},{"source":"RPT","target":"RPT","count":11},{"source":"RPT","target":"RTR","count":1},{"source":"RWWA","target":"INT","count":1},{"source":"RWWA","target":"ITS","count":1},{"source":"RWWA","target":"PER","count":1},{"source":"RWWA","target":"RWWA","count":1},{"source":"SCOR","target":"SCOR","count":5},{"source":"SPK","target":"INT","count":4},{"source":"SPK","target":"ITS","count":4},{"source":"SPK","target":"SPK","count":21},{"source":"TS","target":"CS","count":1},{"source":"TS","target":"TS","count":10}]; var nodes_data = [{"name":"ABS","total":11},{"name":"ATS","total":23},{"name":"CR","total":25},{"name":"ENV","total":3},{"name":"INT","total":78},{"name":"ITS","total":177},{"name":"PDG","total":28},{"name":"PER","total":33},{"name":"PRAC","total":4},{"name":"AC","total":2},{"name":"ACDC","total":1},{"name":"APL","total":10},{"name":"LA","total":20},{"name":"PEG","total":53},{"name":"AST","total":21},{"name":"COP","total":2},{"name":"DBT","total":3},{"name":"DEVOPS","total":1},{"name":"IGN","total":18},{"name":"CAR","total":11},{"name":"LOT","total":18},{"name":"ICS","total":1},{"name":"NRB","total":4},{"name":"ONT","total":1},{"name":"INFRA","total":1},{"name":"RPT","total":11},{"name":"RTR","total":1},{"name":"RWWA","total":1},{"name":"SCOR","total":5},{"name":"SPK","total":21},{"name":"CS","total":1},{"name":"TS","total":10}]; //create node size scale var nodeSizeScale = d3.scaleLinear() .domain(d3.extent(nodes_data, d => d.total)) .range([30, 70]); //create node size scale var linkSizeScale = d3.scaleLinear() .domain(d3.extent(links_data, d => d.count)) .range([5, 30]); //create node size scale var linkColourScale = d3.scaleLinear() .domain(d3.extent(links_data, d => d.count)) .range(['blue', 'red']); //document.getElementsByTagName('body')[0].innerHTML = '<div>' + JSON.stringify(nodes_data) + '</div>'; //create somewhere to put the force directed graph var height = 650, width = 950; var svg = d3.select("body").append("svg") .attr('width',width) .attr('height',height); var radius = 15; //set up the simulation and add forces var simulation = d3.forceSimulation() .nodes(nodes_data); var link_force = d3.forceLink(links_data) .id(function(d) { return d.name; }) ; var charge_force = d3.forceManyBody() .strength(-1000); var center_force = d3.forceCenter(width / 2, height / 2); simulation .force("charge_force", charge_force) .force("center_force", center_force) .force("link",link_force) ; //add tick instructions: simulation.on("tick", tickActions ); // THIS CODE SECTION ISN'T RENDERING // Per-type markers, as they don't inherit styles. svg.append("defs").selectAll("marker") .data(["dominating"]) .enter().append("marker") .attr("id", function (d) { return d; }) .attr("viewBox", "0 -5 10 10") .attr("refX", 15) .attr("refY", -1.5) .attr("markerWidth", 12) .attr("markerHeight", 12) .attr("orient", "auto") .append("path") .attr("d", "M0,-5L10,0L0,5"); //add encompassing group for the zoom var g = svg.append("g") .attr("class", "everything"); // add the curved links to our graphic var link = g.selectAll(".link") .data(links_data) .enter() .append("path") .attr("class", "link") .style('stroke', d => {return linkColourScale(d.count);}) .attr('stroke-opacity', 0.5) .attr('stroke-width', d => {return linkSizeScale(d.count);}); //draw circles for the nodes var node = g.append("g") .attr("class", "nodes") .selectAll("circle") .data(nodes_data) .enter() .append("circle") .attr("r", d => {return nodeSizeScale(d.total);}) .attr("fill", "#333") .on("mouseover", mouseOver(.1)) .on("mouseout", mouseOut); //add text labels var text = g.append("g") .attr("class", "labels") .selectAll("text") .data(nodes_data) .enter().append("text") .style("text-anchor","middle") .style("font-weight", "bold") .style("pointer-events", "none") .attr("dy", ".35em") .text(function(d) { return d.name }); //add drag capabilities var drag_handler = d3.drag() .on("start", drag_start) .on("drag", drag_drag) .on("end", drag_end); drag_handler(node); //add zoom capabilities var zoom_handler = d3.zoom() .on("zoom", zoom_actions); zoom_handler(svg); /** Functions **/ //Drag functions //d is the node function drag_start(d) { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; } //make sure you can't drag the circle outside the box function drag_drag(d) { d.fx = d3.event.x; d.fy = d3.event.y; } function drag_end(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; } //Zoom functions function zoom_actions(){ g.attr("transform", d3.event.transform) } function tickActions() { //update circle positions each tick of the simulation node .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); //update link positions link.attr("d", positionLink); text.attr("x", function(d) { return d.x; }) .attr("y", function(d) { return d.y; }); } // links are drawn as curved paths between nodes, // through the intermediate nodes function positionLink(d) { var offset = 30; var midpoint_x = (d.source.x + d.target.x) / 2; var midpoint_y = (d.source.y + d.target.y) / 2; var dx = (d.target.x - d.source.x); var dy = (d.target.y - d.source.y); var normalise = Math.sqrt((dx * dx) + (dy * dy)); var offSetX = midpoint_x + offset * (dy / normalise); var offSetY = midpoint_y - offset * (dx / normalise); return "M" + d.source.x + "," + d.source.y + "S" + offSetX + "," + offSetY + " " + d.target.x + "," + d.target.y; } // build a dictionary of nodes that are linked var linkedByIndex = {}; links_data.forEach(function(d) { linkedByIndex[d.source.index + "," + d.target.index] = 1; }); // check the dictionary to see if nodes are linked function isConnected(a, b) { return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index] || a.index == b.index; } // fade nodes on hover function mouseOver(opacity) { return function(d) { // check all other nodes to see if they're connected // to this one. if so, keep the opacity at 1, otherwise // fade node.style("stroke-opacity", function(o) { thisOpacity = isConnected(d, o) ? 1 : opacity; return thisOpacity; }); node.style("fill-opacity", function(o) { thisOpacity = isConnected(d, o) ? 1 : opacity; return thisOpacity; }); text.style("fill-opacity", function(o) { thisOpacity = isConnected(d, o) ? 1 : opacity; return thisOpacity; }); // also style link accordingly link.style("stroke-opacity", function(o) { return o.source === d || o.target === d ? 1 : opacity; }); link.style("stroke", function(o) { return o.source === d || o.target === d ? linkColourScale(o.count) : "#333"; }); }; } function mouseOut() { node.style("stroke-opacity", 1); node.style("fill-opacity", 1); text.style("fill-opacity", 1); link.style("stroke-opacity", 0.5); link.style("stroke", d => {return linkColourScale(d.count);}); }
I have applied the same code changes in the example you referred, to your code and it seems to work fine. The only extra update required was, since you had nodes connecting to itself, I had to apply marker-end property and path length updates only to the filtered set of links. var links_data = [{"source":"ABS","target":"ABS","count":8},{"source":"ABS","target":"ATS","count":1},{"source":"ABS","target":"CR","count":8},{"source":"ABS","target":"ENV","count":1},{"source":"ABS","target":"INT","count":16},{"source":"ABS","target":"ITS","count":9},{"source":"ABS","target":"PDG","count":1},{"source":"ABS","target":"PER","count":4},{"source":"ABS","target":"PRAC","count":3},{"source":"AC","target":"AC","count":1},{"source":"AC","target":"INT","count":9},{"source":"AC","target":"ITS","count":1},{"source":"ACDC","target":"ACDC","count":1},{"source":"ACDC","target":"CR","count":2},{"source":"ACDC","target":"ITS","count":13},{"source":"ACDC","target":"PER","count":4},{"source":"APL","target":"APL","count":8},{"source":"APL","target":"CR","count":3},{"source":"APL","target":"ENV","count":1},{"source":"APL","target":"INT","count":1},{"source":"APL","target":"ITS","count":29},{"source":"APL","target":"LA","count":1},{"source":"APL","target":"PEG","count":1},{"source":"APL","target":"PER","count":3},{"source":"AST","target":"AST","count":17},{"source":"AST","target":"COP","count":1},{"source":"AST","target":"DBT","count":2},{"source":"AST","target":"DEVOPS","count":1},{"source":"AST","target":"IGN","count":1},{"source":"AST","target":"INT","count":2},{"source":"AST","target":"ITS","count":32},{"source":"AST","target":"PDG","count":2},{"source":"AST","target":"PER","count":8},{"source":"ATS","target":"ABS","count":1},{"source":"ATS","target":"ATS","count":21},{"source":"ATS","target":"DBT","count":1},{"source":"ATS","target":"INT","count":3},{"source":"ATS","target":"PDG","count":1},{"source":"ATS","target":"PEG","count":1},{"source":"CAR","target":"APL","count":1},{"source":"CAR","target":"CAR","count":9},{"source":"CAR","target":"COP","count":1},{"source":"CAR","target":"INT","count":9},{"source":"CAR","target":"ITS","count":8},{"source":"IGN","target":"CR","count":4},{"source":"IGN","target":"IGN","count":13},{"source":"IGN","target":"INT","count":5},{"source":"IGN","target":"ITS","count":13},{"source":"IGN","target":"PER","count":4},{"source":"IGN","target":"PRAC","count":1},{"source":"LA","target":"AC","count":1},{"source":"LA","target":"INT","count":1},{"source":"LA","target":"ITS","count":37},{"source":"LA","target":"LA","count":18},{"source":"LA","target":"PER","count":2},{"source":"LOT","target":"LOT","count":18},{"source":"PDG","target":"ABS","count":1},{"source":"PDG","target":"AST","count":4},{"source":"PDG","target":"ATS","count":1},{"source":"PDG","target":"CAR","count":1},{"source":"PDG","target":"CR","count":8},{"source":"PDG","target":"ICS","count":1},{"source":"PDG","target":"IGN","count":3},{"source":"PDG","target":"INT","count":18},{"source":"PDG","target":"ITS","count":6},{"source":"PDG","target":"NRB","count":4},{"source":"PDG","target":"ONT","count":1},{"source":"PDG","target":"PDG","count":24},{"source":"PDG","target":"PER","count":1},{"source":"PEG","target":"CAR","count":1},{"source":"PEG","target":"ENV","count":1},{"source":"PEG","target":"INFRA","count":1},{"source":"PEG","target":"ITS","count":22},{"source":"PEG","target":"LA","count":1},{"source":"PEG","target":"PEG","count":51},{"source":"PEG","target":"PER","count":6},{"source":"RPT","target":"ABS","count":1},{"source":"RPT","target":"APL","count":1},{"source":"RPT","target":"IGN","count":1},{"source":"RPT","target":"INT","count":9},{"source":"RPT","target":"ITS","count":2},{"source":"RPT","target":"RPT","count":11},{"source":"RPT","target":"RTR","count":1},{"source":"RWWA","target":"INT","count":1},{"source":"RWWA","target":"ITS","count":1},{"source":"RWWA","target":"PER","count":1},{"source":"RWWA","target":"RWWA","count":1},{"source":"SCOR","target":"SCOR","count":5},{"source":"SPK","target":"INT","count":4},{"source":"SPK","target":"ITS","count":4},{"source":"SPK","target":"SPK","count":21},{"source":"TS","target":"CS","count":1},{"source":"TS","target":"TS","count":10}]; var nodes_data = [{"name":"ABS","total":11},{"name":"ATS","total":23},{"name":"CR","total":25},{"name":"ENV","total":3},{"name":"INT","total":78},{"name":"ITS","total":177},{"name":"PDG","total":28},{"name":"PER","total":33},{"name":"PRAC","total":4},{"name":"AC","total":2},{"name":"ACDC","total":1},{"name":"APL","total":10},{"name":"LA","total":20},{"name":"PEG","total":53},{"name":"AST","total":21},{"name":"COP","total":2},{"name":"DBT","total":3},{"name":"DEVOPS","total":1},{"name":"IGN","total":18},{"name":"CAR","total":11},{"name":"LOT","total":18},{"name":"ICS","total":1},{"name":"NRB","total":4},{"name":"ONT","total":1},{"name":"INFRA","total":1},{"name":"RPT","total":11},{"name":"RTR","total":1},{"name":"RWWA","total":1},{"name":"SCOR","total":5},{"name":"SPK","total":21},{"name":"CS","total":1},{"name":"TS","total":10}]; //create node size scale var nodeSizeScale = d3.scaleLinear() .domain(d3.extent(nodes_data, d => d.total)) .range([30, 70]); //create node size scale var linkSizeScale = d3.scaleLinear() .domain(d3.extent(links_data, d => d.count)) .range([5, 30]); //create node size scale var linkColourScale = d3.scaleLinear() .domain(d3.extent(links_data, d => d.count)) .range(['blue', 'red']); //document.getElementsByTagName('body')[0].innerHTML = '<div>' + JSON.stringify(nodes_data) + '</div>'; //create somewhere to put the force directed graph var height = 650, width = 950; var svg = d3.select("body").append("svg") .attr('width',width) .attr('height',height); var radius = 15; //set up the simulation and add forces var simulation = d3.forceSimulation() .nodes(nodes_data); var link_force = d3.forceLink(links_data) .id(function(d) { return d.name; }) ; var charge_force = d3.forceManyBody() .strength(-1000); var center_force = d3.forceCenter(width / 2, height / 2); simulation .force("charge_force", charge_force) .force("center_force", center_force) .force("link",link_force) ; //add tick instructions: simulation.on("tick", tickActions ); // THIS CODE SECTION ISN'T RENDERING // Per-type markers, as they don't inherit styles. svg.append("defs").selectAll("marker") .data(["dominating"]) .enter().append("marker") .attr('markerUnits', 'userSpaceOnUse') .attr("id", function (d) { return d; }) .attr("viewBox", "0 -5 10 10") .attr("refX", 0) .attr("refY", 0) .attr("markerWidth", 12) .attr("markerHeight", 12) .attr("orient", "auto-start-reverse") .append("path") .attr("d", "M0,-5L10,0L0,5") .attr("fill", "red"); //add encompassing group for the zoom var g = svg.append("g") .attr("class", "everything"); // add the curved links to our graphic var link = g.selectAll(".link") .data(links_data) .enter() .append("path") .attr("class", "link") .style('stroke', d => {return linkColourScale(d.count);}) .attr('stroke-opacity', 0.5) .attr('stroke-width', d => {return linkSizeScale(d.count);}) .attr("marker-end", function(d) { if(JSON.stringify(d.target) !== JSON.stringify(d.source)) return "url(#dominating)"; }); //draw circles for the nodes var node = g.append("g") .attr("class", "nodes") .selectAll("circle") .data(nodes_data) .enter() .append("circle") .attr("r", d => {return nodeSizeScale(d.total);}) .attr("fill", "#333") .on("mouseover", mouseOver(.1)) .on("mouseout", mouseOut); //add text labels var text = g.append("g") .attr("class", "labels") .selectAll("text") .data(nodes_data) .enter().append("text") .style("text-anchor","middle") .style("font-weight", "bold") .style("pointer-events", "none") .attr("dy", ".35em") .text(function(d) { return d.name }); //add drag capabilities var drag_handler = d3.drag() .on("start", drag_start) .on("drag", drag_drag) .on("end", drag_end); drag_handler(node); //add zoom capabilities var zoom_handler = d3.zoom() .on("zoom", zoom_actions); zoom_handler(svg); /** Functions **/ //Drag functions //d is the node function drag_start(d) { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; } //make sure you can't drag the circle outside the box function drag_drag(d) { d.fx = d3.event.x; d.fy = d3.event.y; } function drag_end(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; } //Zoom functions function zoom_actions(){ g.attr("transform", d3.event.transform) } function tickActions() { //update circle positions each tick of the simulation node .attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); //update link positions link.attr("d", positionLink1); link.filter(function(d){ return JSON.stringify(d.target) !== JSON.stringify(d.source); }) .attr("d",positionLink2); text.attr("x", function(d) { return d.x; }) .attr("y", function(d) { return d.y; }); } function positionLink1(d) { var dx = d.target.x - d.source.x, dy = d.target.y - d.source.y, dr = Math.sqrt(dx * dx + dy * dy); return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y; } // recalculate and back off the distance function positionLink2(d) { // length of current path var pl = this.getTotalLength(), // radius of circle plus marker head r = nodeSizeScale(d.target.total)+ 12, //12 is the "size" of the marker Math.sqrt(12**2 + 12 **2) // position close to where path intercepts circle m = this.getPointAtLength(pl - r); var dx = m.x - d.source.x, dy = m.y - d.source.y, dr = Math.sqrt(dx * dx + dy * dy); return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + m.x + "," + m.y; } // build a dictionary of nodes that are linked var linkedByIndex = {}; links_data.forEach(function(d) { linkedByIndex[d.source.index + "," + d.target.index] = 1; }); // check the dictionary to see if nodes are linked function isConnected(a, b) { return linkedByIndex[a.index + "," + b.index] || linkedByIndex[b.index + "," + a.index] || a.index == b.index; } // fade nodes on hover function mouseOver(opacity) { return function(d) { // check all other nodes to see if they're connected // to this one. if so, keep the opacity at 1, otherwise // fade node.style("stroke-opacity", function(o) { thisOpacity = isConnected(d, o) ? 1 : opacity; return thisOpacity; }); node.style("fill-opacity", function(o) { thisOpacity = isConnected(d, o) ? 1 : opacity; return thisOpacity; }); text.style("fill-opacity", function(o) { thisOpacity = isConnected(d, o) ? 1 : opacity; return thisOpacity; }); // also style link accordingly link.style("stroke-opacity", function(o) { return o.source === d || o.target === d ? 1 : opacity; }); link.style("stroke", function(o) { return o.source === d || o.target === d ? linkColourScale(o.count) : "#333"; }); }; } function mouseOut() { node.style("stroke-opacity", 1); node.style("fill-opacity", 1); text.style("fill-opacity", 1); link.style("stroke-opacity", 0.5); link.style("stroke", d => {return linkColourScale(d.count);}); } body { width:99%; height:100%; background: #111111; } .svg { width:1000; height:1000; } .link { fill: none; } .labels { font-family: Arial; fill: white; } <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
How to initiate zoomability in a Sunburst with selection from dropdown
I have a sunburst for which I would like to initiate zoom ability via dropdown. That is when a country name is selected from the drop down menu its part in the sunburst zooms exactly like when its clicked. js fiddle: http://jsfiddle.net/8wd2xt9n/7/ var width = 960, height = 700, radius = Math.min(width, height) / 2; var b = { w: 130, h: 30, s: 3, t: 10 }; var x = d3.scale.linear() .range([0, 2 * Math.PI]); var y = d3.scale.sqrt() .range([0, radius]); var changeArray = [100,80,60,0, -60, -80, -100]; var colorArray = ["#67000d", "#b73e43", "#d5464a", "#f26256", "#fb876e", "#fca78e", "#fcbba1", "#fee0d2", "#fff5f0"]; var svg = d3.select("#diagram").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + (height / 2 + 10) + ")"); var partition = d3.layout.partition() .value(function(d) { return d.Total; }); var arc = d3.svg.arc() .startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); }) .endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); }) .innerRadius(function(d) { return Math.max(0, y(d.y)); }) .outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); }); console.log(arc) function checkIt(error, root){ initializeBreadcrumbTrail(); //intilaize dropdown if (error) throw error; var g = svg.selectAll("g") .data(partition.nodes(root)) .enter().append("g"); var path = g.append("path") .attr("d", arc) .style("fill", function(d) { var color; if(d.Total_Change > 100) {color = colorArray[0] } else if(d.Total_Change > 0 && d.Total_Change < 100) {color = colorArray[1] } else { color = colorArray[2] } d.color = color; return color}) .on("click", click) .on("mouseover", mouseover); var tooltip = d3.select("body") .append("div") .attr("id", "tooltips") .style("position", "absolute") .style("background-color", "#fff") .style("z-index", "10") .style("visibility", "hidden"); g.on("mouseover", function(d){return tooltip.style("visibility", "visible") .html("<div class=" + "tooltip_container>"+"<h4 class=" + "tooltip_heading>" +d.name.replace(/[_-]/g, " ") +"</h4>" +"<br>" + "<p> Emissions 2013:" + " " + "<br>" + d.Total + " " +"<span>in Million Tons</span></p>"+ "<br>"+ "<p> Change in Emissions: <span>" + (d.Total_Change/d.Total*100).toPrecision(3) + "%" + "</span></p>"+"</div>" );}) .on("mousemove", function(){return tooltip.style("top",(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");}) .on("mouseout", function(){return tooltip.style("visibility", "hidden");}); //creating a dropdown var dropDown = d3.select("#dropdown_container") .append("select") .attr("class", "selection") .attr("name", "country-list"); var nodeArr = partition.nodes(root); var options = dropDown.selectAll("option") .data(nodeArr) .enter() .append("option"); options.text(function (d) { var prefix = new Array(d.depth + 1); var dropdownValues = d.name.replace(/[_-]/g, " "); return dropdownValues; }).attr("value", function (d) { var dropdownValues = d.name; return dropdownValues; }); // transition on click function click(d) { // fade out all text elements path.transition() .duration(750) .attrTween("d", arcTween(d)) .each("end", function(e, i) { // check if the animated element's data e lies within the visible angle span given in d if (e.x >= d.x && e.x < (d.x + d.dx)) { // get a selection of the associated text element var arcText = d3.select(this.parentNode).select("text"); // fade in the text element and recalculate positions arcText.transition().duration(750) .attr("opacity", 1) .attr("transform", function() { return "rotate(" + computeTextRotation(e) + ")" }) .attr("x", function(d) { return y(d.y); }); } }); }; d3.select(".selection").on("change", function changePie() { var value = this.value; var index = this.selectedIndex; var dataObj = nodeArr[index]; path[0].forEach(function(p){ var data = d3.select(p).data();//get the data from the path if (data[0].name === value){ path.transition() .duration(750) .attrTween("d", arcTween(d)) .each("end", function(e, i) { // check if the animated element's data e lies within the visible angle span given in d if (e.x >= d.x && e.x < (d.x + d.dx)) { // get a selection of the associated text element var arcText = d3.select(this.parentNode).select("text"); // fade in the text element and recalculate positions arcText.transition().duration(750) .attr("opacity", 1) .attr("transform", function() { return "rotate(" + computeTextRotation(e) + ")" }) .attr("x", function(d) { return y(d.y); }); } }); } }); console.log(this.value + " :c " + dataObj["Iron and steel"] + " in " + (dataObj.parent && dataObj.parent.name)); }); }; d3.json("https://gist.githubusercontent.com/heenaI/cbbc5c5f49994f174376/raw/55c672bbca7991442f1209cfbbb6ded45d5e8c8e/data.json", checkIt); d3.select(self.frameElement).style("height", height + "px"); // Interpolate the scales! function arcTween(d) { var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]), yd = d3.interpolate(y.domain(), [d.y, 1]), yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]); return function(d, i) { return i ? function(t) { return arc(d); } : function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); return arc(d); }; }; } function initializeBreadcrumbTrail() { // Add the svg area. var trail = d3.select("#sequence").append("svg:svg") .attr("width", width) .attr("height", 50) .attr("id", "trail"); // Add the label at the end, for the percentage. trail.append("svg:text") .attr("id", "endlabel") .style("fill", "#000"); } function breadcrumbPoints(d, i) { var points = []; points.push("0,0"); points.push(b.w + ",0"); points.push(b.w + b.t + "," + (b.h / 2)); points.push(b.w + "," + b.h); points.push("0," + b.h); if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex. points.push(b.t + "," + (b.h / 2)); } return points.join(" "); } // Update the breadcrumb trail to show the current sequence and percentage. function updateBreadcrumbs(nodeArray) { // Data join; key function combines name and depth (= position in sequence). var g = d3.select("#trail") .selectAll("g") .data(nodeArray, function(d) { return d.name.replace(/[_-]/g, " ") + d.Total; }); // Add breadcrumb and label for entering nodes. var entering = g.enter().append("svg:g"); entering.append("svg:polygon") .attr("points", breadcrumbPoints) .style("fill", "#d3d3d3"); entering.append("svg:text") .attr("x", (b.w + b.t) / 2) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .text(function(d) { return d.name.replace(/[_-]/g, " "); }); // Set position for entering and updating nodes. g.attr("transform", function(d, i) { return "translate(" + i * (b.w + b.s) + ", 0)"; }); // Remove exiting nodes. g.exit().remove(); // Now move and update the percentage at the end. d3.select("#trail").select("#endlabel") .attr("x", (nodeArray.length + 0.5) * (b.w + b.s)) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle"); // Make the breadcrumb trail visible, if it's hidden. d3.select("#trail") .style("visibility", ""); } function getAncestors(node) { var path = []; var current = node; while (current.parent) { path.unshift(current); current = current.parent; } return path; } function mouseover(d) { var sequenceArray = getAncestors(d); updateBreadcrumbs(sequenceArray);}
Add this one line and it will work :) Inside your selection change add this var d = data[0]; as shown below: d3.select(".selection").on("change", function changePie() { var value = this.value; var index = this.selectedIndex; var dataObj = nodeArr[index]; path[0].forEach(function(p){ var data = d3.select(p).data();//get the data from the path if (data[0].name === value){ var d = data[0];//this line is missing path.transition() Working code here Other option is to call the click function on selection change like below d3.select(".selection").on("change", function changePie() { var value = this.value; var index = this.selectedIndex; var dataObj = nodeArr[index]; path[0].forEach(function (p) { var data = d3.select(p).data(); //get the data from the path if (data[0].name === value) { console.log(data) click(data[0]);//call the click function } Working code here Hope this helps!
Don't rotate nodes in radial tree layout in d3.js
Fiddle Example I can't figure out how to tweak the transform:rotate attribute for the nodes so that the pictures and text in the foreign objects don't rotate/ go upside down. I have tried tweaking with this block of code: var nodeUpdate = node.transition() .duration(duration) .attr("transform", function (d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; }); In the Chrome Console, I change a node from <g transform="translate(226.5247584249853,-164.57987064189248)rotate(-36)"> <foreignObject.....></foreignObject></g> to transform="translate(226.5247584249853,-164.57987064189248)rotate(0) and it works. But changing rotate to 0 in the code above would make every children node go to the left side., like this Full code: treeData = myJSON; // Calculate total nodes, max label length var totalNodes = 0; var maxLabelLength = 0; // variables for drag/drop var selectedNode = null; var draggingNode = null; // panning variables var panSpeed = 200; var panBoundary = 20; // Within 20px from edges will pan when dragging. // Misc. variables var i = 0; var duration = 750; var root; // size of the diagram var width = $(document).width(); var height = $(document).height(); var diameter = 800; var tree = d3.layout.tree().size([360, diameter / 2 - 120]) .separation(function (a, b) { return (a.parent == b.parent ? 1 : 10) / a.depth; }); // define a d3 diagonal projection for use by the node paths later on. var diagonal = d3.svg.diagonal.radial() .projection(function (d) { return [d.y, d.x / 180 * Math.PI]; }); // Define the root root = treeData; root.x0 = height / 2; root.y0 = 0; // A recursive helper function for performing some setup by walking through all nodes function visit(parent, visitFn, childrenFn) { if (!parent) return; visitFn(parent); var children = childrenFn(parent); if (children) { var count = children.length; for (var i = 0; i < count; i++) { visit(children[i], visitFn, childrenFn); } } } // Call visit function to establish maxLabelLength visit(treeData, function (d) { totalNodes++; maxLabelLength = Math.max(d.name.length, maxLabelLength); }, function (d) { return d.children && d.children.length > 0 ? d.children : null; }); // sort the tree according to the node names function sortTree() { tree.sort(function (a, b) { return b.name.toLowerCase() < a.name.toLowerCase() ? 1 : -1; }); } // Sort the tree initially incase the JSON isn't in a sorted order. sortTree(); // TODO: Pan function, can be better implemented. function pan(domNode, direction) { var speed = panSpeed; if (panTimer) { clearTimeout(panTimer); translateCoords = d3.transform(svgGroup.attr("transform")); if (direction == 'left' || direction == 'right') { translateX = direction == 'left' ? translateCoords.translate[0] + speed : translateCoords.translate[0] - speed; translateY = translateCoords.translate[1]; } else if (direction == 'up' || direction == 'down') { translateX = translateCoords.translate[0]; translateY = direction == 'up' ? translateCoords.translate[1] + speed : translateCoords.translate[1] - speed; } scaleX = translateCoords.scale[0]; scaleY = translateCoords.scale[1]; scale = zoomListener.scale(); svgGroup.transition().attr("transform", "translate(" + translateX + "," + translateY + ")scale(" + scale + ")"); d3.select(domNode).select('g.node').attr("transform", "translate(" + translateX + "," + translateY + ")"); zoomListener.scale(zoomListener.scale()); zoomListener.translate([translateX, translateY]); panTimer = setTimeout(function () { pan(domNode, speed, direction); }, 50); } } // Define the zoom function for the zoomable tree function zoom() { svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); } // define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents var zoomListener = d3.behavior.zoom().scaleExtent([1, 1]).on("zoom", zoom); function initiateDrag(d, domNode) { draggingNode = d; d3.select(domNode).select('.ghostCircle').attr('pointer-events', 'none'); d3.selectAll('.ghostCircle').attr('class', 'ghostCircle show'); d3.select(domNode).attr('class', 'node activeDrag'); svgGroup.selectAll("g.node").sort(function (a, b) { // select the parent and sort the path's if (a.id != draggingNode.id) return 1; // a is not the hovered element, send "a" to the back else return -1; // a is the hovered element, bring "a" to the front }); // if nodes has children, remove the links and nodes if (nodes.length > 1) { // remove link paths links = tree.links(nodes); nodePaths = svgGroup.selectAll("path.link") .data(links, function (d) { return d.target.id; }).remove(); // remove child nodes nodesExit = svgGroup.selectAll("g.node") .data(nodes, function (d) { return d.id; }).filter(function (d, i) { if (d.id == draggingNode.id) { return false; } return true; }).remove(); } // remove parent link parentLink = tree.links(tree.nodes(draggingNode.parent)); svgGroup.selectAll('path.link').filter(function (d, i) { if (d.target.id == draggingNode.id) { return true; } return false; }).remove(); dragStarted = null; } // define the baseSvg, attaching a class for styling and the zoomListener var baseSvg = d3.select("#tree-container").append("svg") .attr("width", width) .attr("height", height) .attr("class", "overlay") .call(zoomListener); // Define the drag listeners for drag/drop behaviour of nodes. dragListener = d3.behavior.drag() .on("dragstart", function (d) { if (d == root) { return; } dragStarted = true; nodes = tree.nodes(d); d3.event.sourceEvent.stopPropagation(); // it's important that we suppress the mouseover event on the node being dragged. Otherwise it will absorb the mouseover event and the underlying node will not detect it d3.select(this).attr('pointer-events', 'none'); }) .on("drag", function (d) { if (d == root) { return; } if (dragStarted) { domNode = this; initiateDrag(d, domNode); } // get coords of mouseEvent relative to svg container to allow for panning relCoords = d3.mouse($('svg').get(0)); if (relCoords[0] < panBoundary) { panTimer = true; pan(this, 'left'); } else if (relCoords[0] > ($('svg').width() - panBoundary)) { panTimer = true; pan(this, 'right'); } else if (relCoords[1] < panBoundary) { panTimer = true; pan(this, 'up'); } else if (relCoords[1] > ($('svg').height() - panBoundary)) { panTimer = true; pan(this, 'down'); } else { try { clearTimeout(panTimer); } catch (e) { } } d.x0 = d3.event.x; d.y0 = d3.event.y; var node = d3.select(this); node.attr("transform", "translate(" + d.x0 + "," + (d.y0) + ")"); updateTempConnector(); }) .on("dragend", function (d) { if (d == root) { return; } domNode = this; if (selectedNode) { // now remove the element from the parent, and insert it into the new elements children var index = draggingNode.parent.children.indexOf(draggingNode); if (index > -1) { draggingNode.parent.children.splice(index, 1); } if (typeof selectedNode.children !== 'undefined' || typeof selectedNode._children !== 'undefined') { if (typeof selectedNode.children !== 'undefined') { selectedNode.children.push(draggingNode); } else { selectedNode._children.push(draggingNode); } } else { selectedNode.children = []; selectedNode.children.push(draggingNode); } // Make sure that the node being added to is expanded so user can see added node is correctly moved expand(selectedNode); sortTree(); endDrag(); } else { endDrag(); } }); function endDrag() { selectedNode = null; d3.selectAll('.ghostCircle').attr('class', 'ghostCircle'); d3.select(domNode).attr('class', 'node'); // now restore the mouseover event or we won't be able to drag a 2nd time d3.select(domNode).select('.ghostCircle').attr('pointer-events', ''); updateTempConnector(); if (draggingNode !== null) { update(root); //centerNode(draggingNode); draggingNode = null; } } // Helper functions for collapsing and expanding nodes. function collapse(d) { if (d.children) { d._children = d.children; d._children.forEach(collapse); d.children = null; } } function expand(d) { if (d._children) { d.children = d._children; d.children.forEach(expand); d._children = null; } } var overCircle = function (d) { console.log(d); selectedNode = d; updateTempConnector(); }; var outCircle = function (d) { selectedNode = null; updateTempConnector(); }; // Function to update the temporary connector indicating dragging affiliation var updateTempConnector = function () { var data = []; if (draggingNode !== null && selectedNode !== null) { // have to flip the source coordinates since we did this for the existing connectors on the original tree data = [{ source: { x: $('svg g').first().offset().left + selectedNode.position.left, y: selectedNode.position.top }, target: { x: draggingNode.x0, y: draggingNode.y0 } }]; } var link = svgGroup.selectAll(".templink").data(data); link.enter().append("path") .attr("class", "templink") .attr("d", d3.svg.diagonal.radial()) .attr('pointer-events', 'none'); link.attr("d", d3.svg.diagonal.radial()); link.exit().remove(); }; // Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children. function centerNode(source) { scale = zoomListener.scale(); x = -source.x0; y = -source.y0; x = x * scale + width / 2; y = y * scale + height / 2; d3.select('g').transition() .duration(duration) .attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")"); zoomListener.scale(scale); zoomListener.translate([x, y]); } // Toggle children function function toggleChildren(d) { if (d.children) { d._children = d.children; d.children = null; } else if (d._children) { d.children = d._children; d._children = null; } return d; } // Toggle children on click. function click(d) { if (d3.event.defaultPrevented) return; // click suppressed d = toggleChildren(d); update(d); //centerNode(d); //dofocus([{ name : 'o_id' , value : d.o_id }]); } function update(source) { // Compute the new height, function counts total children of root node and sets tree height accordingly. // This prevents the layout looking squashed when new nodes are made visible or looking sparse when nodes are removed // This makes the layout more consistent. 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, root); //var newHeight = d3.max(levelWidth) * 25; // 25 pixels per line // tree = tree.size([newHeight, width]); // Compute the new tree layout. var nodes = tree.nodes(root); //.reverse(), links = tree.links(nodes); // Set widths between levels based on maxLabelLength. // nodes.forEach(function(d) { // d.y = (d.depth * (maxLabelLength * 10)); //maxLabelLength * 10px // // alternatively to keep a fixed scale one can set a fixed depth per level // // Normalize for fixed-depth by commenting out below line // // d.y = (d.depth * 500); //500px per level. // }); // Update the nodes… node = svgGroup.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") .call(dragListener) .attr("class", "node") // .attr("transform", function(d) { // return "translate(" + source.y0 + "," + source.x0 + ")"; // }) .on('click', click) nodeEnter.append("foreignObject") .attr("class", "smallcircle") .attr("width", function (d) { var f = document.createElement("span"); f.id = "hiddenText"; f.style.display = 'hidden'; f.style.padding = '0px'; f.innerHTML = d.name; document.body.appendChild(f); textWidth = f.offsetWidth; var f1 = document.getElementById('hiddenText'); f1.parentNode.removeChild(f1); return textWidth + 50; }) .attr("overflow", "visible") .attr("height", 50) .attr("y", - 50 / 2) .attr("x", - 50) .append("xhtml:div").attr("class", "mainDiv") .html(function (d) { var htmlString = ""; htmlString += "<div class='userImage' style='border-color:red '><img src='https://www.gravatar.com/avatar/6d2db975d856b8799a6198bab4777aed?s=32&d=identicon&r=PG' width='50' height='50'></div>"; htmlString += "<div class='content' style='color:red;'>" + d.name + "</div>"; htmlString += "<div style='clear:both;'></div>"; return htmlString; }) nodeEnter.append("text") .text(function (d) { return d.name; }) .style("font", "8px serif") .style("opacity", 0.9) .style("fill-opacity", 0); // phantom node to give us mouseover in a radius around it nodeEnter.append("circle") .attr('class', 'ghostCircle') .attr("r", 30) .attr("opacity", 0.2) // change this to zero to hide the target area .style("fill", "red") .attr('pointer-events', 'mouseover') .on("mouseover", function (node) { node.position = $(this).position(); node.offset = $(this).offset(); overCircle(node); }) .on("mouseout", function (node) { outCircle(node); }); // Update the text to reflect whether node has children or not. // node.select('text') // .attr("x", function(d) { // return d.children || d._children ? -10 : 10; // }) // .attr("text-anchor", function(d) { // return d.children || d._children ? "end" : "start"; // }) // .text(function(d) { // return d.name; // }); // Change the circle fill depending on whether it has children and is collapsed node.select("circle.nodeCircle") .attr("r", 4.5) .style("fill", function (d) { return d._children ? "lightsteelblue" : "#fff"; }); var nodeUpdate = node.transition() .duration(duration) .attr("transform", function (d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; }); nodeUpdate.select("circle") .attr("r", 4.5) .style("fill", function (d) { return d._children ? "lightsteelblue" : "#fff"; }); // Fade the text in // nodeUpdate.select("text") // .style("fill-opacity", 1); nodeUpdate.select("text") .style("fill-opacity", 1) // .attr("transform", function(d) { return d.x < 180 ? "translate(0)" : "rotate(180)translate(-" + (d.name.length + 50) + ")"; }) .attr("dy", ".35em") .attr("text-anchor", function (d) { return d.x < 180 ? "start" : "end"; }) .attr("transform", function (d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; }); // Transition exiting nodes to the parent's new position. var nodeExit = node.exit().transition() .duration(duration) .attr("transform", function (d) { return "translate(" + source.x + "," + source.y + ")"; }) .remove(); nodeExit.select("circle") .attr("r", 0); nodeExit.select("text") .style("fill-opacity", 0); // Update the links… var link = svgGroup.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; }); } // Append a group which holds all nodes and which the zoom Listener can act upon. var svgGroup = baseSvg.append("g").attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")"); // Collapse all children of roots children before rendering. root.children.forEach(function (child) { collapse(child); }); // Layout the tree initially and center on the root node. update(root); d3.select(self.frameElement).style("height", width);
The rotation is set in line 1221 of your fiddle: return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; The rotation here is required for the positioning, as you're rotating around the origin of the non-translated coordinate system. So simply removing the rotate(...) won't work. However, you can rotate the elements back after positioning: return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")rotate(" + (-d.x + 90) + ")"; Complete fiddle here.