Adding label to the links in D3 force directed graph - javascript

I have created a force directed graph but I'm unable to add text to the links created.
How can I do so?
Following is my code link
I have used the following line to append the titles on the link's, but its not coming.
link.append("title")
.text(function (d) {
return d.value;
});
What am I doing wrong with this ?

This link contains the solution that you need.
The key point here is that "title" adds tooltip. For label, you must provide slightly more complex (but not overly complicated) code, like this one from the example from the link above:
// Append text to Link edges
var linkText = svgCanvas.selectAll(".gLink")
.data(force.links())
.append("text")
.attr("font-family", "Arial, Helvetica, sans-serif")
.attr("x", function(d) {
if (d.target.x > d.source.x) {
return (d.source.x + (d.target.x - d.source.x)/2); }
else {
return (d.target.x + (d.source.x - d.target.x)/2); }
})
.attr("y", function(d) {
if (d.target.y > d.source.y) {
return (d.source.y + (d.target.y - d.source.y)/2); }
else {
return (d.target.y + (d.source.y - d.target.y)/2); }
})
.attr("fill", "Black")
.style("font", "normal 12px Arial")
.attr("dy", ".35em")
.text(function(d) { return d.linkName; });
The idea of the code is simple: It calculates the midpoint of the link, and displays some text at that place (you can decide what that text actually is). There are some additional calculations and conditions, you can figure it out from the code, however you'll anyway want to change them depending on your needs and aesthetics.
EDIT: Important note here is that "gLink" is the name of the class of links, previously defined with this code:
// Draw lines for Links between Nodes
var link = svgCanvas.selectAll(".gLink")
.data(force.links())
In your example, it may be different, you need to adjust the code.
Here is a guide how to incorporate solution from example above to another example of force layout that doesn't have link labels:
SVG Object Organization and Data Binding
In D3 force-directed layouts, layout must be supplied with array of nodes and links, and force.start() must be called. After that, visual elements may be created as requirements and desing say. In our case, following code initializes SVG "g" element for each link. This "g" element is supposed to contain a line that visually represent link, and the text that corresponds to that link as well.
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter()
.append("g")
.attr("class", "link")
.append("line")
.attr("class", "link-line")
.style("stroke-width", function (d) {
return Math.sqrt(d.value);
});
var linkText = svg.selectAll(".link")
.append("text")
.attr("class", "link-label")
.attr("font-family", "Arial, Helvetica, sans-serif")
.attr("fill", "Black")
.style("font", "normal 12px Arial")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
});
"g" elements have class "link", lines have class "link-line", ad labels have class "link-label". This is done so that "g" elements may be easily selected, and lines and labels can be styled in CSS file conveninetly via classes "link-line" and "link-label" (though such styling is not used in this example).
Initialization of positions of lines and text is not done here, since they will be updated duting animation anyway.
Force-directed Animation
In order for animation to be visible, "tick" function must contain code that determine position of lines and text:
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; });
linkText
.attr("x", function(d) {
return ((d.source.x + d.target.x)/2);
})
.attr("y", function(d) {
return ((d.source.y + d.target.y)/2);
});
Here is the resulting example: plunker

Related

Transitioning Text in D3

I'm trying to add text to nodes that are created dynamically, specifically, like this graph:
http://bl.ocks.org/mbostock/999346
I am NOT looking to add text to collapsible graphs, but to add text to graphs that insert nodes at runtime, as shown in the above example.
So far I have the following additional code:
node.enter().append("text", "g")
.attr("x", function(d) { return (d.x);})
.attr("y", function(d) { return (d.y);})
.text(function(d) { return d.name; })
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; });
This adds text but it doesn't move when nodes are inserted.
The below lines appear to move the nodes and links in the example:
var t = svg.transition()
.duration(duration);
t.selectAll(".link")
.attr("d", diagonal);
t.selectAll(".node")
.attr("cx", function(d) { return d.px = d.x; })
.attr("cy", function(d) { return d.py = d.y; });
but adding a similar function for text:
t.selectAll(".text")
.style("fill-opacity", 1);
has no effect.
I would very much appreciate any guidance on this matter.
The nodes are all identified with d3.selectAll('.node'), so you need to give them the node class.
Also, the cx and cy attributes don't exist on text elements. you want x and y instead.
Example fiddle is here.

D3 Hive plot highlight Node and its links

I've been playing around with mbostock's D3 hive plot from here, and I would like to upgrade it to have similar functionalities as this example. That is, when I mouseover a node, all its links should be highlighted, as well as text that shows from where and to where these links come from/go to.
I manage highlighting the individual nodes and links without a problem using for example
svg.selectAll(".link")
.data(lLinks)
.enter().append("path")
.on("mouseover", function() {
d3.select(this)
.transition()
.duration(150)
.style("stroke-width", 3)
})
but I am having trouble figuring out how to highlight all the links belonging to a particular node.
My current data structure is practically the same as mbostock's, which I assume is ill suited for what I am trying to do.
How should I go about upgrading this code to highlight all the links and show their source/destination?
here's a working fiddle: http://jsfiddle.net/boatrokr/rk2s5/
Below is the code for the node selection. As you can see, all I did was select the links and if the link source or destination matched the selected node, the stroke width of the link gets set to 5. I'm not sure if this is the best way to do it, but it works. - edit: I forgot to remove a console.log in there - needed it for dev :)
svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("transform", function(d) { return "rotate(" + degrees(angle(d.x)) + ")"; })
.attr("cx", function(d) { return radius(d.y); })
.attr("r", 5)
.style("fill", function(d) { return color(d.x); })
.on("mouseover", function(d) {
d3.select(this)
.transition()
.duration(150)
.style("stroke-width", 3)
d3.selectAll(".link")
.data(links)
.style("stroke-width", function (dl) {
if(dl.source == d){
console.log(dl);
return 5;
}else if(dl.target == d){
return 5;
}
});
})
.on("mouseout", function(){
d3.select(this)
.style("stroke-width", 1.5)
d3.selectAll(".link")
.style("stroke-width", 1.5)
});

d3: use anchor elements as chart labels

I am getting started with D3 and SVG but I haven't found anything clear on how to add hyperlinks. Here is some code I have to write labels to the left of the bars in a D3 bar chart. Is there a good sample somewhere to convert these labels to hyperlinks (say objects in rangeData had an href and name/label property)? I searched around a bit but haven't gotten much further than the svg spec for adding an anchor element.
chart.selectAll(".bar.barLabel")
.data(rangeData)
.enter().append("text")
.attr("class", "bar")
.attr("x", 0)
.attr("y", function (d, i) { return height(i) + barHeight(y, i) / 2; })
.attr("dx", -20)
.attr("dy", ".35em")
.attr("text-anchor", "end")
.text(function (d) { return d.label; });
You can use the a element to achieve this, very similar to HTML itself. You wrap the content in the a element and provide the link target as the href attribute with xlink namespace.
chart.selectAll("a")
.data(rangeData)
.enter()
.append("a")
.attr("xlink:href", function(d) { return d.href; })
.append("text")
.text(function (d) { return d.label; });
Alternatively, you could use the foreignObject element to directly embed HTML into your SVG.

Update line order (z-orientation) on mouseover in d3

I am new to using d3 and JavaScript and would appreciate some constructive feedback. I'm mocking up a practice example to learn d3 that involves plotting climate data (temperature anomaly) from 1880-2010 from two sources (GISS and HAD). So far I have generated a multiple line chart in d3 using this data. Code and data are here https://gist.github.com/natemiller/0c3659e0e6a0b77dabb0
In this example the data are originally plotted grey, but each line colored a different color on mouseover.
I would like to add two additional features.
I would like, on mouseover, to reorder the lines so that the moused-over line is on top, essentially reorder the lines. I've read that this requires essentially replotting the SVG and I have tried code along the lines of this
source.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", "lightgrey")
.on("mouseover", function() {
if (active) active.classed("highlight", false);
active = d3.select(this.parentNode.appendChild(this))
.classed("highlight", true);
})
.style("stroke",function(d) {return color(d.name);})
.on("mouseout", function(d) {
d3.select('#path-' + d.name)
.transition()
.duration(750)
.style("stroke", "lightgrey")
})
.attr("id", function(d, i) { return "path-" + d.name; });
where the .on("mouseover"... code is meant to highlight the current "moused-over" line. It doesn't seem to work in my example. All the lines are highlighted initially and then turn grey with the mouseover/mouseout. If someone could help me identify how to update my code so that I can reorder the lines on mouseover that would be great!
I have been playing around with labeling the lines such that when either the line or its label is moused-over the line and label colors update. I've played around a bit using id's but so far I can't get both the text and the line to change color. I've managed to 1. mouseover the line and change the color of the text, 2. mouseover the text and change the color of the line, 2. mouseover the line and change the line, but not have both the line and the text change color when either of them are moused-over. Here is a section of code that serves as a start (using ids), but doesn't quite work as it only specifies the path, but not the text and the path. I've tried adding them both to d3.select('#path-','#text-'..., and variations on this, but it doesn't seem to work.
source.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", "lightgrey")
.on("mouseover", function(d){
d3.select(this)
.style("stroke",function(d) {return color(d.name);});
})
.on("mouseout", function(d) {
d3.select('#path-' + d.name)
.transition()
.duration(750)
.style("stroke", "lightgrey")
})
.attr("id", function(d, i) { return "path-" + d.name; });
source.append("text")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 15]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")"; })
.attr("x", 5)
.attr("dy", ".35em")
.style("stroke", "lightgrey")
.on("mouseover", function(d){
d3.select('#path-' + d.name)
.style("stroke",function(d) {return color(d.name);});
})
.on("mouseout", function(d) {
d3.select('#path-' + d.name)
.transition()
.duration(750)
.style("stroke", "lightgrey")
})
.text(function(d) { return d.name; })
.attr("font-family","sans-serif")
.attr("font-size","11px")
.attr("id", function(d, i) { return "text-" + d.name; });
I greatly appreciate your help. I am new to d3 and this help-serve. Its a steep learning curve at the moment, but I hope this example and the code is reasonably clear. If its not let me know how I can make it better and I can repost the question.
Thanks so much,
Nate
Chris Viau provided a good answer to this question over on the d3 Google group.
https://groups.google.com/forum/?fromgroups=#!topic/d3-js/-Ra66rqHGk4
The trick is to select the path's g parent to reorder it with the others:
this.parentNode.parentNode.appendChild(this.parentNode);
This appends the current selection's container "g" on top of all the other "g".
I've found this useful in lots of other instances as well.
Thanks Chris!

links in d3.js forced directed graph

In this example, how can I make the text of each node to be a clickable link?
I tried something similar to this code, but the values were not clickable:
var links = text.append("a").attr("xlink:href", "http://www.google.com/");
// A copy of the text with a thick white stroke for legibility.
links.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class", "shadow")
.text(function(d) { return d.name; });
links.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.text(function(d) { return d.name; });
EDIT / SOLUTION: turns out the css had this attriubte: pointer-events: none;
I had to delete it and then use as Elijah suggested.
Don't use links, drop it and append directly to your text <g> and it should work.
text.append("svg:text")
.attr("x", 8)
.attr("y", ".31em")
.attr("class", "shadow")
.text(function(d) { return d.name; })
.on("click", function() {yourFunction(yourVar)})
.on("mouseover", function() {yourFunction2(yourVar)})
.on("mouseout", function() {yourFunction3(yourVar)})
;
Also, if you want to pass the bound data, you'd do that like this:
.on("click", function(d) {yourFunction(d.yourVar)}
Whereas if you want to pass the actual d object, you can do it like this:
.on("click", yourFunction}
In which case yourFunction(d,i) can then reference d.whatever from your bound data.

Categories