C2Task3ToyForceDirected

Basic force directed layout

by Simon Raper

HTML

<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<div id ="chart"></div>

CSS

.node {
    stroke: #fff;
    stroke-width: 1.5px;
}
.link {
    stroke: #999;
    stroke-opacity: .6;
}

JavaScript

//Data

graph  = {
    "nodes": [{
        "name": "squishedfish.com",
        "group": 1
    }, {
        "name": "reddog.co.uk",
        "group": 1
    }, {
        "name": "blankcat.com",
        "group": 2
    }, {
        "name": "scrimpledfeet.com",
        "group": 2
    }, {
        "name": "sickbag.com",
        "group": 2
    }, {
        "name": "bluehouse.co.uk",
        "group": 3
    }, {
        "name": "webbedcat.com",
        "group": 3
    }, {
        "name": "flatrhino.co.uk",
        "group": 1
    }, {
        "name": "greycamel.com",
        "group": 3
    }  ],
        "links": [{
        "source": 0,
            "target": 1,
            "value": 20
    }, {
        "source": 0,
            "target": 2,
            "value": 30
    }, {
        "source": 1,
            "target": 4,
            "value": 22
    }, {
        "source": 6,
            "target": 2,
            "value": 5
    }, {
        "source": 1,
            "target": 7,
            "value": 5
    }, {
        "source": 3,
            "target": 8,
            "value": 15
    }, {
        "source": 5,
            "target": 8,
            "value": 15
    }]
};

//Constants for the SVG
var width = 500,
    height = 500;

//Set up the force layout
var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);

//Append a SVG to the body of the html page. Assign this SVG as an object to svg
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);


//Creates the graph data structure out of the json data
force.nodes(graph.nodes)
    .links(graph.links)
    .start();

//Create all the line svgs but without locations yet
var link = svg.selectAll(".link")
    .data(graph.links)
    .enter().append("line")
    .attr("class", "link")
    .style("stroke-width", function (d) {
    return Math.sqrt(d.value);
});

//Do the same with the circles for the nodes - no 
var node = svg.selectAll(".node")
   ...