D3 Hive plot highlight Node and its links - javascript

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)
});

Related

Adding label to the links in D3 force directed graph

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

maintaining the layering of elements after adding new elements

I'm drawing a little clickable graph data browser.
Example:
First, I load a few movies, and I see this:
Then, after I click on one of the nodes (Hellraiser, in this case), I use ajax to load additional related information properties and values, and end up with this:
The lines and circles of the newly added nodes are obviously drawn after the originally clicked node was.
Here is the draw method that gets called every time new data is ready to be added to the graph:
function draw() {
force.start();
//Create edges as lines
var edges = svg.selectAll("line")
.data(dataset.edges)
.enter()
.append("line")
.style("stroke", "#ccc")
.style("stroke-width", 2)
.on("mouseover", lineMouseover)
.on("mouseout", lineMouseout);
//create the nodes
var node = svg.selectAll(".node")
.data(dataset.nodes)
.enter()
.append("g")
.attr("class", "node")
.on("click", callback)
.attr("r", function(d, i) { //custom sizes based on datatype
if(d.datatype && (d.datatype in _design) ) {
return _design[d.datatype].size;
} else {
return _design["other"].size;
}
})
.call(force.drag);
//create fancy outlines on the nodes
node.append("circle")
.attr("r", function(d,i) { //custom sizes based on datatype
if(d.datatype && (d.datatype in _design) ) {
return _design[d.datatype].size * r;
} else {
return _design["other"].size * r;
}
})
.style("stroke", "black")
.style("stroke-width", 3)
.style("fill", function(d, i) { //custom color based on datatype
if(d.datatype && (d.datatype in _design) ) {
return _design[d.datatype].color;
} else {
return _design["other"].color;
}
})
.attr("class","circle");
//Add text to each node.
node.append("text")
.attr("dx", 0)
.attr("dy", ".25em")
//.attr("class", "outline")
.attr("fill", "black")
.text(function(d, i) {
return d.name;//d.name
});
};
How do I go about drawing those lines underneath the clicked node?
You can group the different kinds of elements below g elements that you can create at the beginning in the required order. This way, anything you append to them later will be ordered correctly:
var links = svg.append("g"),
nodes = svg.append("g"),
labels = svg.append("g");
// ...
var edges = links.selectAll("line")
.data(dataset.edges)
.enter()
.append("line");
var node = nodes.selectAll(".node")
.data(dataset.nodes)
.enter()
.append("g")
// etc.

d3js: adding same type of elements with different data

//add circles with price data
svgContainer.selectAll("circle")
.data(priceData)
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y1(d); })
//add circles with difficulty data
svgContainer.selectAll("circle")
.data(difficultyData)
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y2(d); })
In the first half, circles with price data are added along the relevant line in the graph chart. Now I want to do the same with the second half to add circles with different data to a different line. However, the first circles' data are overwritten by the second circles' data, and the second circles never get drawn.
I think I have a gut feeling of what's going on here, but can someone explain what exactly is being done and how to solve the problem?
possible reference:
"The key function also determines the enter and exit selections: the
new data for which there is no corresponding key in the old data
become the enter selection, and the old data for which there is no
corresponding key in the new data become the exit selection. The
remaining data become the default update selection."
First, understand what selectAll(), data(), enter() do from this great post.
The problem is that since circle element already exists by the time we get to the second half, the newly provided data simply overwrites the circles instead of creating new circles. To prevent this from happening, you need to specify a key function in data() function of the second half. Then, the first batch of circles do not get overwritten.
//add circles with price data
svgContainer.selectAll("circle")
.data(priceData)
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y1(d); })
//add circles with difficulty data
svgContainer.selectAll("circle")
.data(difficultyData, function(d) { return d; }) // SPECIFY KEY FUNCTION
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y2(d); })
you can append the circles in two different groups, something like:
//add circles with price data
svgContainer.append("g")
.attr("id", "pricecircles")
.selectAll("circle")
.data(priceData)
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y1(d); })
//add circles with difficulty data
svgContainer.append("g")
.attr("id", "datacircles")
.selectAll("circle")
.data(difficultyData)
.enter()
.append("svg:circle")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y2(d); })
if the circles are in different groups they won't be overwritten
I had the same question as OP. And, I figured out a solution similar to tomtomtom above. In short: Use SVG group element to do what you want to do with different data but the same type of element. More explanation about why SVG group element is so very useful in D3.js and a good example can be found here:
https://www.dashingd3js.com/svg-group-element-and-d3js
My reply here includes a jsfiddle of an example involving 2 different datasets both visualized simultaneously on the same SVG but with different attributes. As seen below, I created two different group elements (circleGroup1 & circleGroup2) that would each deal with different datasets:
var ratData1 = [200, 300, 400, 600];
var ratData2 = [32, 57, 112, 293];
var svg1 = d3.select('body')
.append('svg')
.attr('width', 500)
.attr('height', 400);
var circleGroup1 = svg1.append("g");
var circleGroup2 = svg1.append("g");
circleGroup1.selectAll("circle")
.data(ratData1)
.enter().append("circle")
.attr("cy", 60)
.attr("cx", function(d, i) { return i * 100 + 30; })
.attr("r", function(d) { return Math.sqrt(d); });
circleGroup2.selectAll("circle")
.data(ratData2)
.enter()
.append("circle")
.attr("r", function(d, i){
return i*20 + 5;
})
.attr("cy", 100)
.attr("cx", function(d,i){ return i*100 +30;})
.style('fill', 'red')
.style('fill-opacity', '0.3');
What is happening is that you are:
In the FIRST HALF:
getting all circle elements in the svg container. This returns nothing because it is the first time you're calling it so there are no circle elements yet.
then you're joining to data (by index, the default when you do not specify a key function). This puts everything in the priceData dataset in the "enter" section.
Then you draw your circles and everything is happy.
then, In the SECOND SECTION:
You are again selecting generically ALL circle elements, of which there are (priceData.length) elements already existing in the SVG.
You are joining a totally different data set to these elements, again by index because you did not specify a key function. This is putting (priceData.length) elements into the "update section" of the data join, and either:
if priceData.length > difficultyData.length, it is putting (priceData.length - difficulty.length) elements into the "exit section"
if priceData.length < difficultyData.length, it is putting (difficulty.length - priceData.length) elements into the "enter section"
Either way, all of the existing elements from the first "priceData" half are reused and have their __data__ overwritten with the new difficultyData using an index-to-index mapping.
Solution?
I don't think a key function is what you are looking for here. A key function is way to choose a unique field in the data on which to join data instead of index, because index does not care if the data or elements are reordered, etc. I would use this when i want to make sure a single data set is correctly mapped back to itself when i do a selectAll(..).data(..).
The solution I would use for your problem is to group the circles with a style class so that you are creating two totally separate sets of circles for your different data sets. See my change below.
another option is to nest the two groups of circles each in their own "svg:g" element, and set a class or id on that element. Then use that element in your selectAll.. but generally, you need to group them in some way so you can select them by those groupings.
//add circles with price data
svgContainer.selectAll("circle.price")
.data(priceData)
.enter()
.append("svg:circle")
.attr("class", "price")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y2(d); })
//add circles with difficulty data
svgContainer.selectAll("circle.difficulty")
.data(difficultyData)
.enter()
.append("svg:circle")
.attr("class", "difficulty")
.attr("r", 6)
.style("fill", "none")
.style("stroke", "none")
.attr("cx", function(d, i) {
return x(convertDate(dates[i]));
})
.attr("cy", function(d) { return y2(d); })
Using this method, you will always be working with the correct circle elements for the separate datasets. After that, if you have a better unique value in the data than simply using the index, you can also add a custom key function to the two .data(..) calls.

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!

How do I add a title attribute to the nodes of my force-directed graph generated by d3?

Following a d3 demonstration (http://goo.gl/lN7Jo), I am trying to create a force-directed graph. I am trying to add a title attribute to my node elements created by doing this.
var node = svg.selectAll("circle.node")
.data(json.nodes)
.enter().append("circle")
.attr("class", "node")
// here is how I try to add a title.
.attr("title", "my title")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag);
However, the nodes of my graph are not displaying a title attribute. What is the proper way to do so? Thank you.
In SVG title attributes are really elements that describe their parent, so you would have to follow the example you linked...
var node = svg.selectAll("circle.node")
.data(json.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag);
node.append("title")
.text("my text");
Add this code right below where you initialise your node. This will add some hard-code text as title to each node.
node.append("title")
.text("my text");
If you want to add name as title, do this;
node.append("title")
.text(function (d) {
return d.name;
})

Categories