Force Layout Graphs in D3 Module 7

This page is a reference for viewers of my Force Layout Graphs in D3 course on

If you don’t have an account on Pluralsight you can get a free trial here: Free Trial on

Pulling in External Data

  • Use one of D3’s built-in data consumers (eg. d3.csv())
  • Parse data into node and link objects


// Compute the distinct nodes from the links.
links.forEach(function(link) {
link.source = nodes[link.source] ||
(nodes[link.source] = {name: link.source}); = nodes[] ||
(nodes[] = {name:});
link.value = +link.value;

Using Images for Nodes

  • Instead of drawing SVG shapes use an image
  • Ideally the image would be svg as well and scale


// add the images
.attr("xlink:href", function(d) {
return "img/"".png"; })
.attr("x", function(d) { return -25;})
.attr("y", function(d) { return -25;})
.attr("height", 50)
.attr("width", 50);

Styling Links

  • Use external data to define style for link (eg. win or loss)
  • Use CSS to adjust style

Example: {
fill: none;
stroke-width: 2px;
} {
stroke: #a6d96a; //green
} {
stroke: #ca0020; //red
} {
stroke: #ca0020; //red

Adding Labels

  • Append text to nodes
  • Style with CSS


// add the text
.attr("text-anchor", "middle")
.attr("dy", ".35em")
.attr("class", "label")
.text(function(d) { return; });

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


//add hovercard
var hovercard ="body").append("div")
.attr("class", "hovercard")
.style("opacity", 0)     //set to 0 to start
// adjust during tick function
function tick(e) { ...
.style("opacity", 1);
var tip = <insert hmtl>...
.style("left", (d3.event.pageX) + "px")                    .style("top", (d3.event.pageY) + "px");

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