Curved line on d3 force directed tree - javascript

New to d3 and trying to develop a force directed tree into which we can plug varioss dataset. I've managed to get the basic idea up and running but would like to make the links curved so I can deal with multiple links. I've looked at http://bl.ocks.org/1153292 and I'm just not getting it. The nearest I get is it all working with no path visible. This is my code for straight lines, I'd appreciate some help if you've got the time
Thanks:
//Sets up the svg that holds the data structure and puts it in the div called mapBox
var svg = d3.select("div#mapBox.theMap").append("svg")
.attr("width", mapWidth)
.attr("height", mapHeight);
//Sets up the data structure and binds the data to it
var force = d3.layout.force()
.nodes(data.nodes)
.links(data.links)
.size([mapWidth, mapHeight])
.charge(-600)
.linkDistance(60)
.start();
//Draws the links and set up their styles
var link = svg.selectAll("link")
.data(data.links)
.enter().append("line")
.attr("class", "link")
.style("stroke", "#ccc")
//Creates nodes and attached "g" element to append other things to
var node = svg.selectAll(".node")
.data(data.nodes)
.enter().append("g")
.call(force.drag);
//Appends the cirdle to the "g" element and defines styles
node.append("circle")
.attr("r", function(d) { if (d.weight<1.1) {return 5} else {return d.weight*1.3+5 }})
.style("fill", "White")
.style("stroke-width", 3)
.style("stroke", function(d) { if (d.type==1) {return "#eda45e "} if(d.type==2) {return "#819e9a"}else {return "#c36256" }} ) // Node stroke colors
.on("mouseover", nodeMouseover)
on("mouseout", nodeMouseout)
.on("mousedown", nodeMousedown)
.call(force.drag);
//Appends text to the "g" element and defines styles
node.append("text")
.attr("class", "nodetext")
.attr("dx", 16)
.attr("dy", ".35em")
.attr("text-anchor", function(d) { if (d.type==1) {return "middle";} else {return "start";} })
.text(function(d) { return d.name })
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});

Der, worked it out.
change
.enter().append("line")
to
.enter().append("path")
then change
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
to
link.attr("d", function(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;
});
Hope that help anyone stuck as I was

This also worked for me.
First define a path:
var path = vis.selectAll("path")
.data(force.links());
path.enter().insert("svg:path")
.attr("class", "link")
.style("stroke", "#ccc");
Then define the curve, as Bob Haslett says and in the Mobile Patent Suits example:
path.attr("d", function(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;
});

Related

D3 curved link with arrow not appearing on screen

I am trying to add the curved links with the arrow as per this d3noob's block to my codepen.
After adding 2 nodes (Add Node button) and selecting the source node and target node from the select boxes when I press the Add Link button it does not show the link, however, the nodes readjust on the screen giving an idea that a link has been created.
I added the following code (including some variable definitions in codepen)
path.attr("d", function(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;
});
it was earlier :
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
It's because you haven't actually created any objects to change the attributes of, you tried to create the paths off of the force links at the top of your file, before any links had actually been created. You needed to create the paths based on the links in your 'restart' function and then update their attributes in the 'tick' function. Here's a codepen: https://codepen.io/anon/pen/RBazVp?editors=0010
Here's the relevant changes:
function restart() {
...
...
link = link.data(links);
link.enter()
.append('path')
.attr('class', 'link');
link.exit().remove();
force.start();
...
...
}
function tick() {
link.attr("d", function(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
);
});
...
...
}
To add arrows to the links:
var arrows = svg.append("defs")
.selectAll("marker")
.data(["arrow"])
.enter()
.append("marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5");
function restart() {
...
...
link = link.data(links);
link.enter()
.append('path')
.attr('class', 'link')
.attr('marker-end', 'url(#arrow)');
link.exit().remove();
force.start();
...
...
}
Interestingly, you only need to define and create the arrow once, and changing the 'marker-end' attribute will automatically generate another copy of the arrow. Pretty neat!

How do I change the position of a circle svg element using the transform attribute?

I am currently building a sunburst chart in D3JS and am trying to append circles to each node. You can view current project here: https://jsfiddle.net/mhxuo260/.
I am trying to position each of the circles in the top right hand corner of their respective node. Currently they will only position in the center which covers the node labels. I have been scouring the net in search for a clue but just haven't come up with anything yet. Any suggestion would be appreciated.
d3.json("flare.json", function(error, root) {
if (error) throw error;
var g = svg.selectAll("g")
.data(partition.nodes(root))
.enter().append("g");
path = g.append("path")
.attr("d", arc)
.attr('stroke', 'white')
.attr("fill", function(d) { return color((d.children ? d : d.parent).name); })
.on("click", magnify)
.each(stash);
var text = g.append("text")
// .attr("x", function(d) { return d.x; })
// .attr("dx", "6") // margin
// .attr("dy", ".35em") // vertical-align
.text(function(d) {
return d.name;
})
.attr('font-size', function(d) {
return '10px';
})
.attr("text-anchor", "middle")
.attr("transform", function(d) {
if (d.depth > 0) {
return "translate(" + arc.centroid(d) + ")" +
"rotate(" + getStartAngle(d) + ")";
} else {
return null;
}
})
.on("click", magnify);
var circle = g.append('circle')
.attr('cx', function(d) { return d.x })
.attr('cy', function(d) { return d.dy; })
.attr('r', '10')
.attr('fill', 'white')
.attr('stroke', 'lightblue')
.attr("transform", function(d) {
console.log(arc.centroid(d))
if (d.depth > 0) {
return "translate(" + arc.centroid(d) + ")" +
"rotate(" + getStartAngle(d) + ")";
} else {
return null;
}
});
You are using the ´´´arc.centroid´´´ function which always returns the x,y midpoint of the arc. All that function is doing is:
The midpoint is defined as (startAngle + endAngle) / 2 and (innerRadius + outerRadius) / 2
You just need to calculate a different position using these values depending on where you want it. Use the transform like this (sudo code):
.attr( "transform", function(d) {
var x = (startAngle + endAngle) / 2;
var y = (innerRadius + outerRadius) / 2;
return "translate(" + x +"," + y + ")";
});
You don't need to rotate your circle.
(FYI: javascript will convert arrays into strings by joining each number with commas, this is why arc.centroid returning an array works here)

How to make nodes in sankey diagram clickable using d3.js library

Code Snippet :
We are using d3.js for this.
Sankey diagrams is made up of nodes and links.
Here the data comes from json file.
So how to make all the nodes clickable.
Which methods can we use with the rectangles so that we can make the nodes clickable.
<script>
var margin = {top: 1, right: 1, bottom: 6, left: 1},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatNumber = d3.format(",.0f"), //decimal places
format = function(d) { return formatNumber(d) + " TWh"; },
color = d3.scale.category20();
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.size([width, height]);
var path = sankey.link();
//d3.json("energy.json", function(energy) {
d3.json("numbers-subset.json", function(energy) {
sankey
.nodes(energy.nodes)
.links(energy.links)
.layout(32);
var link = svg.append("g").selectAll(".link")
.data(energy.links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.sort(function(a, b) { return b.dy - a.dy; });
link.append("title")
.text(function(d) { return d.source.name + " → " + d.target.name + "\n" + format(d.value); });
var node = svg.append("g").selectAll(".node")
.data(energy.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() { this.parentNode.appendChild(this); })
.on("drag", dragmove));
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function(d) { return d.color = color(d.name.split("|")[0]); })
.style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
.append("title")
.text(function(d) { return d.name + "\n" + format(d.value); });
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) { return d.name; })
.filter(function(d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
function dragmove(d) {
d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
sankey.relayout();
link.attr("d", path);
}
});
</script>
D3.js is very powerful library give you control over each event to each pixel.
but we need to do one thing in the case of events.
Overlapping event we need to by forget .
Add following code in code.
var node = svg.append("g").selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; })
.on("click",function(d){
if (d3.event.defaultPrevented) return;
alert("clicked!"+d.value);
})
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() {
this.parentNode.appendChild(this); })
.on("drag", dragmove));

Adding hover effect in d3 word cloud

I am using D3 Cloud to build a word cloud (https://github.com/jasondavies/d3-cloud) and I would like to add an hover effect similar to http://www.jasondavies.com/wordcloud.
Here is the sample code. Complete code is at http://plnkr.co/edit/gNtHZ0lMRTP98mptm3W8?p=preview
var sizeScale = d3.scale.linear()
.domain([0, d3.max(frequency_list, function(d) { return d.freq} )]).range([10, 95]);
layout = d3.layout.cloud().size([w, h])
.words(frequency_list)
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d) { return sizeScale(d.freq); })
.on("end",draw)
.start();
}
function draw(words) {
var fill = d3.scale.category20();
d3.select(container).remove();
d3.select("body").append(container)
.attr("width", w)
.attr("height", h)
.append("g")
.attr("transform", "translate(" + [w/2, h/2] + ")")
.selectAll("text")
.data(words)
.enter().append("text")
.transition()
.duration(function(d) { return d.time} )
.attr('opacity', 1)
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "rotate(" + d.rotate + ")";
})
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
On the page you link to, he's using a :hover pseudo-class.
<style>
text:hover { opacity: .7 !important; }
</style>
Updated code here.

Unable to get click event in D3 JavaScript library

I am using D3 JavaScript library to display data as a force directed marker. It works fine. But I am unable to add click event to the circle. so when I click on the circle, I get detailed analysis of the circle and display it in a modal box.
var links = [{source: "x", target:"y", type: "paid"},......]';
var nodes = {};
// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
});
var w = 950,
h = 500;
var force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([w, h])
.linkDistance(60)
.charge(-300)
.on("tick", tick)
.start();
var svg = d3.select("#graph").append("svg:svg")
.attr("width", w)
.attr("height", h);
// Per-type markers, as they don't inherit styles.
svg.append("svg:defs").selectAll("marker")
.data(["suit", "licensing", "resolved"])
.enter().append("svg:marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("refY", -1.5)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
var path = svg.append("svg:g").selectAll("path")
.data(force.links())
.enter().append("svg:path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.call(force.drag);
var text = svg.append("svg:g").selectAll("g")
.data(force.nodes())
.enter().append("svg:g");
// A copy of the text with a thick white stroke for legibility.
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class", "shadow")
.text(function(d) { return d.name; });
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
// Use elliptical arc path segments to doubly-encode directionality.
function tick() {
path.attr("d", function(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;
});
circle.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
text.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
I tried adding .on("click", 'alert(\'Hello world\')') to var circle. It does not work as expected. It alerts on load instead on click.
I appreciate any help
Try this:
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.on("click", function(d,i) { alert("Hello world"); })
.call(force.drag);
Try out this, if you want the node contained within the circle (let's say that your nodes are mapping an object with a key called anger and a value 34:
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.on("click", function(d,i) { alert(d.anger); }) // this will alert 34
.call(force.drag);
Or try this for the attributes of the svg (getting the radius of the svg, for example):
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", 6)
.on("click", function(d,i) { alert(d3.select(this).r; }) // this will print out the radius })
.call(force.drag);
Sorry if my post is like the one above, but I thought the clarification could be useful.

Categories