This page is a reference for viewers of my Force Layout Graphs in D3 course on Pluralsight.com
If you don't have an account on Pluralsight you can get a free trial here: Free Trial on Pluralsight.com
Pulling in External Data
- Use one of D3's built-in data consumers (eg. d3.csv())
- Parse data into node and link objects
Example:
[code]
// 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});
link.value = +link.value;
});
[/code]
Using Images for Nodes
- Instead of drawing SVG shapes use an image
- Ideally the image would be svg as well and scale
Example:
[code]
// add the images
node.append(“image”)
.attr(“xlink:href”, function(d) {
return “img/”+d.name.toLowerCase()+”.png”; })
.attr(“x”, function(d) { return -25;})
.attr(“y”, function(d) { return -25;})
.attr(“height”, 50)
.attr(“width”, 50);
[/code]
Styling Links
- Use external data to define style for link (eg. win or loss)
- Use CSS to adjust style
Example:
[code]
path.link {
fill: none;
stroke-width: 2px;
}
path.link.win {
stroke: #a6d96a; //green
}
path.link.loss {
stroke: #ca0020; //red
}
path.link.loss {
stroke: #ca0020; //red
}
[/code]
Adding Labels
- Append text to nodes
- Style with CSS
Example:
[code]
// add the text
node.append(“text”)
.attr(“text-anchor”, “middle”)
.attr(“dy”, “.35em”)
.attr(“y”,-32)
.attr(“class”, “label”)
.text(function(d) { return d.name; });
[/code]
Adding a Hovercard
- Use a hiddent div to build robust tooltips
- Add html and other SVG elements to the tooltip
- on “mouseover” change position and opacity
Example:
[code]
//add hovercard
var hovercard = d3.select(“body”).append(“div”)
.attr(“class”, “hovercard”)
.style(“opacity”, 0) //set to 0 to start
.style(“width”,400);
// adjust during tick function
function tick(e) { …
hovercard.transition()
.duration(500)
.style(“opacity”, 1);
var tip = <insert hmtl>…
hovercard.html(tip)
.style(“left”, (d3.event.pageX) + “px”) .style(“top”, (d3.event.pageY) + “px”);
[/code]
Finishing Touches
- Add a Title to the page
- Use Bootstrap for better styling
Example: Every Game of Thrones Battle Visualized
Thanks for checking out my course! Stay tuned for more from me here and on Pluralsight.com