user1514509
user1514509

Reputation: 11

Creating a force layout in D3.js visualisation library

I'm working on a project, which visualises the references between books. It's worth to mention that I'm a total beginner in Javascript. So, I couldn't get far by reading the D3.js API reference. I used this example code, which works great.

The structure of my CSV file is like this:

source,target
"book 1","book 2"
"book 1","book 3"

etc.

The source and target are connected by a link. These are the points for the layout:

  1. Create two different circles respectively for source and target node.

  2. Set a specific color for source and target node.

  3. The circles should be labeled by the book information, e.g., source node is labeled by "book 1" and target node is labeled by "book 2".

  4. If there is a link between targets, then make this specific link wider than the others links from source to target.

I hope you can help me by creating these points.

Thanks in advance.

Best regards Aeneas

Upvotes: 1

Views: 947

Answers (1)

Sherwin Wu
Sherwin Wu

Reputation: 555

d3.js plays much nicer with json data files than with csv files, so I would recommend transferring your csv data into a json format somehow. I recently coded something similar to this, and I had my nodes and links stored in a json file as a dictionary formatted as such:

{ 
'links': [{'source': 1, 'target': 2, 'value': 0.3}, {...}, ...],
'nodes': [{'name': 'something', 'size': 2}, {...}, ...]
}

This allows you to initialize your nodes and links as follows (after starting the view):

d3.json("data/nodesandlinks.json", function(json) {
var force = self.force = d3.layout.force()
    .nodes(json.nodes)
    .links(json.links)
    .linkDistance(function(d) { return d.value; })
    .linkStrength(function(d) { return d.value; })
    .size([width, height])
    .start();

var link = vis.selectAll("line.link")
    .data(json.links)
    .enter().append("svg:line")
    .attr("class", "link")
    .attr("source", function(d) { return d.source; })
    .attr("target", function(d) { return d.target; })
    .style("stroke-width", function(d) { return d.value; });

var node = vis.selectAll("g.node")
    .data(json.nodes)
    .enter().append("svg:g")
    .attr("class", "node")
    .attr("name", function(d) { return d.name; })
    .call(force.drag);

Hope this helped!

Upvotes: 1

Related Questions