Interacting forces with D3.js - javascript

I'm trying to 'simulate' gravitational forces on particles as they move towards a 'focal' point. Practically speaking, I am trying to modify the following code so that the particles are pulled slightly off-course by the orange node on their way to the blue node. My problem is that I am having trouble conceptualising this using D3.js force directed layouts. I realise this is a pretty vague question, but any help is greatly appreciated! Image and code are below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Force Layouts - Quantitative Foci</title>
<script type="text/javascript" src="http://d3js.org/d3.v2.min.js?2.8.1"></script>
<style type="text/css">
circle {
stroke: #fff;
}
svg {
fill: #fff;
stroke: #000;
}
</style>
</head>
<body>
<div id="body">
<div id="chart"></div>
</div>
<script type="text/javascript">
var w = 1280,
h = 800,
color = d3.scale.category10();
var force = d3.layout.force()
.gravity(0)
.charge(-5)
.linkStrength(0)
.size([w, h]);
var links = force.links(),
nodes = force.nodes(),
centers = [
{type: 0, x: 3 * w / 6, y: 2 * h / 6, fixed: true},
{type: 1, x: 4 * w / 6, y: 4 * h / 6, fixed: true}
];
var svg = d3.select("#chart").append("svg:svg")
.attr("width", w)
.attr("height", h);
svg.append("svg:rect")
.attr("width", w)
.attr("height", h);
svg.selectAll("circle")
.data(centers)
.enter().append("svg:circle")
.attr("r", 12)
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.style("fill", fill)
.call(force.drag);
force.on("tick", function(e) {
var k = e.alpha * .1;
nodes.forEach(function(node) {
var center = centers[node.type];
node.x += (center.x - node.x) * k;
node.y += (center.y - node.y) * k;
});
svg.selectAll("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
svg.selectAll("line")
.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; });
});
var p0;
svg.on("mousemove", function() {
var p1 = d3.svg.mouse(this),
a = {type: 0, x: p1[0], y: p1[1], px: (p0 || (p0 = p1))[0], py: p0[1]},
b = {type: 1, x: centers[1].x, y: centers[1].y, fixed:true},
link = {source: a, target: b};
p0 = p1;
svg.selectAll()
.data([a, b])
.enter().append("svg:circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 4.5)
.style("fill", fill)
.transition()
.delay(3000)
.attr("r", 1e-6)
.remove();
svg.insert("svg:line", "circle")
.data([link])
.transition()
.delay(3000)
.each("end", function() {
nodes.splice(nodes.indexOf(a), 1);
nodes.splice(nodes.indexOf(b), 1);
links.splice(links.indexOf(link), 1);
})
.remove();
nodes.push(a, b);
links.push(link);
force.start();
});
function fill(d) {
return color(d.type);
}
</script>
</body>
</html>
1 http://jsfiddle.net/fbW7T/1/ -- before.
[2] http://jsfiddle.net/fbW7T/2/ -- after, with Lephix' proposal.

First of all, your question is very interesting :).
Replace your force.on("tick", function(e) {...}) with following codes. Actually I just add a variable and 10 lines code in the function.
fr means the radius of a circle zone that particles should off-course from the orange node.
var fr = 100;
force.on("tick", function(e) {
var k = e.alpha * .1;
nodes.forEach(function(node) {
var center = centers[node.type];
node.x += (center.x - node.x) * k;
node.y += (center.y - node.y) * k;
if (node.type == 0) {
center = centers[1];
while (Math.abs(node.x - center.x) < fr && Math.abs(node.y - center.y) < fr) {
if (Math.abs(node.x - center.x) >= Math.abs(node.y - center.y)) {
node.x += (node.x - center.x)/Math.abs(node.x - center.x);
} else {
node.y += (node.y - center.y)/Math.abs(node.y - center.y);
}
}
}
});
svg.selectAll("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
svg.selectAll("line")
.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; });
});

Related

Target SVG path to the middle of rect element

I'm using D3 library to draw an interconnected graph of elements. My nodes are circles and rects connected by oriented line paths.
My problem is that lines pointing to rects element have an ugly visualisation because the line ends on the top-left corner of the rect rather then the center of it (as it does for circles).
How can I make path lines target the center of both circles elements and rect elements?
Code for definition of defs arrow heads:
svg.append('defs')
.append('marker')
.attr('id', 'arrow')
.attr('viewBox', '0 -5 10 10')
.attr('refX', 17) // As far as I understood this provides the distance from the end of the path line.
.attr('refY', -0.1)
.attr('markerWidth', 6)
.attr('markerHeight', 6)
.attr('orient', 'auto')
.attr('fill', function() {
return 'red';
})
.append('path')
.attr('d', 'M0,-5L10,0L0,5');
Definition of oriented links:
let links = svg.selectAll('.link')
.data(data.links)
.enter()
.append('path')
.attr('id', function (d) {
return d.id;
})
.attr('class', 'link')
.attr('fill', 'none')
.attr('stroke-width', 1.2)
.attr('marker-end', 'url(#arrow)')
.attr('stroke', function() {
return 'blue';
})
.style('cursor', 'pointer');
Definition of squares
let squares = svg.selectAll('.square')
.data(data.squares, function(d) {
return d.id;
})
.enter().append('g')
.call(dragger)
.attr('class', 'square')
.style('cursor', 'pointer');
squares.append('rect')
.attr('width', 10)
.attr('height', 10)
.attr('fill', function (d) {
return '#fff';
})
.style('opacity', 0.1)
.style('stroke', function() {
return '#555';
})
.style('stroke-width', '2');
In following screenshot you can see how it behaves. Circles and rects have a low opacity to show up the issue with the path target.
UPDATE
Added tick function definition and usage.
simulation
.nodes(data.nodes)
.on('tick', _tick);
simulation
.force('link')
.distance(80)
.links(data.links);
simulation.alpha(1).restart();
function _tick() {
links.attr('d', function(d) {
let dx = d.target.x - d.source.x;
let dy = d.target.y - d.source.y;
let dr = Math.sqrt(dx * dx + dy * dy);
return ('M' + d.source.x + ',' + d.source.y +
'A' + dr + ',' + dr + ' 0 0,1 ' + d.target.x + ',' + d.target.y);
});
circles.attr('transform', function (d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
squares.attr('transform', function (d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
}
What you have right now is the expected behaviour. In a force simulation (I suppose you're running a force simulation), the tick function changes the x and y properties of the datum object, and you can use them the way you want.
As you didn't shared your tick function, I suppose that you are updating the rectangles' x and y position like this:
squares.attr("x", function(d) {
return d.x
}).attr("y", function(d) {
return d.y
});
If that in fact is correct, the top-left corner of the rectangles correspond to d.x and d.y coordinates. And, since you're using the same properties to draw the path, the paths will go from one top-left corner to the other.
This is easy to show, have a look at this demo:
var width = 200;
var height = 200;
var rectSide = 40;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var nodes = [{
name: "foo",
color: "blue"
}, {
name: "bar",
color: "green"
}, {
name: "baz",
color: "red"
}];
var links = [{
"source": 0,
"target": 1
}, {
"source": 0,
"target": 2
}];
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().distance(100))
.force("charge", d3.forceManyBody().strength(-50))
.force("center", d3.forceCenter(width / 2, height / 2));
var node = svg.selectAll(null)
.data(nodes)
.enter()
.append("rect")
.attr("width", rectSide)
.attr("height", rectSide)
.attr("fill", function(d) {
return d.color
});
var link = svg.selectAll(null)
.data(links)
.enter()
.append("line")
.style("stroke", "#222")
.style("stroke-width", 2);
simulation.nodes(nodes);
simulation.force("link")
.links(links);
simulation.on("tick", function() {
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;
})
node.attr("x", function(d) {
return d.x
}).attr("y", function(d) {
return d.y
});
});
<script src="https://d3js.org/d3.v4.js"></script>
Solution: You can either move the rectangles or the paths.
As your question specifically asks about the paths, the solution is simple: add half-width and half-height to the target and source coordinates:
link.attr("x1", function(d) {
return d.source.x + rectangleWidth / 2;
})
.attr("y1", function(d) {
return d.source.y + rectangleHeight / 2;
})
.attr("x2", function(d) {
return d.target.x + rectangleWidth / 2;
})
.attr("y2", function(d) {
return d.target.y + rectangleHeight / 2;
})
Here is a demo:
var width = 200;
var height = 200;
var rectSide = 40;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var nodes = [{
name: "foo",
color: "blue"
}, {
name: "bar",
color: "green"
}, {
name: "baz",
color: "red"
}];
var links = [{
"source": 0,
"target": 1
}, {
"source": 0,
"target": 2
}];
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().distance(100))
.force("charge", d3.forceManyBody().strength(-50))
.force("center", d3.forceCenter(width / 2, height / 2));
var node = svg.selectAll(null)
.data(nodes)
.enter()
.append("rect")
.attr("width", rectSide)
.attr("height", rectSide)
.attr("fill", function(d) {
return d.color
});
var link = svg.selectAll(null)
.data(links)
.enter()
.append("line")
.style("stroke", "#222")
.style("stroke-width", 2);
simulation.nodes(nodes);
simulation.force("link")
.links(links);
simulation.on("tick", function() {
link.attr("x1", function(d) {
return d.source.x + rectSide / 2;
})
.attr("y1", function(d) {
return d.source.y + rectSide / 2;
})
.attr("x2", function(d) {
return d.target.x + rectSide / 2;
})
.attr("y2", function(d) {
return d.target.y + rectSide / 2;
})
node.attr("x", function(d) {
return d.x
}).attr("y", function(d) {
return d.y
});
});
<script src="https://d3js.org/d3.v4.js"></script>
Can you translate the square? If you can translate it half of the square
width.
Can you find the end of that path on square it like the x2,y2? Plus that half of your square width,.
"hope this inspired you"
squares.append('rect')
.attr('width', 10)
.attr('height', 10)
.attr("transform", "translate(-5,0)")
.attr('fill', function (d) {
return '#fff';
})

D3.js how do I arrange nodes of a force layout to be on a circle

I have developed a force layout to represent relationships between social groups. Now I would like to get the nodes to be distributed in a circle with links joining them. What is the best way to do this?
The complete version of the code (without data) is here http://jsfiddle.net/PatriciaW/zZSJT/
(Why do I have to include code here too? Here is the main portion)
d3.json("/relationships?nocache=" + (new Date()).getTime(),function(error,members){
var links=members.organizations.map(function(members) {
return members.member;
});
var nodes = {};
links.forEach(function(link) {
link.source = nodes[link.xsource] || (nodes[link.xsource] = {source: link.xsource, name: link.xsource, category: link.categorysource, path: link.pathsource, desc: link.descsource, title: link.titlesource});
link.target = nodes[link.xtarget] || (nodes[link.xtarget] = {target: link.xtarget, name: link.xtarget, category: link.categorytarget, path: link.pathtarget, desc: link.desctarget, title: link.titletarget});
});
force = d3.layout.force()
.nodes(d3.values(nodes))
.links(links)
.size([width, height])
.charge(-120)
.linkDistance(function() {return (Math.random() * 200) + 100;})
.linkStrength(0.5)
.on("tick", tick)
.start();
var link = svg.selectAll(".link")
.data(force.links())
.enter().append("line")
.attr("class", "link");
var node_drag = d3.behavior.drag()
.on("dragstart", dragstart)
.on("drag", dragmove)
.on("dragend", dragend);
var loading = svg.append("text")
.attr("x", width / 2)
.attr("y", height / 2)
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text("Simulating. One moment please…");
function dragstart(d, i) {
force.stop() // stops the force auto positioning before you start dragging
}
function dragmove(d, i) {
d.px += d3.event.dx;
d.py += d3.event.dy;
d.x += d3.event.dx;
d.y += d3.event.dy;
tick(); // this is the key to make it work together with updating both px,py,x,y on d !
}
function dragend(d, i) {
d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
tick();
force.resume();
};
var node = svg.selectAll(".node")
.data(force.nodes())
.enter().append("g")
.attr("class", "node")
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.on("click", clickAlert)
.call(node_drag);
node.append("circle")
.attr("r", 8)
.style("fill", function(d) {
return categoryColour [d.category];
})
// add an image marker
node.append("image")
.attr("x",-8)
.attr("y",-8)
.attr("width", 16)
.attr("height", 16)
.attr("xlink:href", function(d) {
return categoryImage [d.category]
})
.on("click", clickAlert)
.style("cursor", "pointer")
node.append("text")
.attr("x", 12)
.attr("dy", ".35em")
.text(function(d) {
return d.name;
});
// Use a timeout to allow the rest of the page to load first.
setTimeout(function() {
// Run the layout a fixed number of times.
// The ideal number of times scales with graph complexity.
force.start();
for (var i = n * n; i > 0; --i) force.tick();
force.stop();
svg.selectAll("line")
.data(links)
.enter().append("line")
.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; });
svg.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 4.5);
loading.remove();
}, 10);
function tick() {
link
.attr("x1", function(d) {
return d.source.x + xadj; })
.attr("y1", function(d) {
return d.source.y + yadj; })
.attr("x2", function(d) {
return d.target.x +xadj; })
.attr("y2", function(d) {
return d.target.y +yadj; });
node
.attr("transform", function(d) {
return "translate(" + (d.x + xadj) + "," + (d.y + yadj) + ")";
});
};
function mouseover() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 16);
d3.select(this).select("text")
.attr("font-size","34px")
.style("font-weight", "bold");
};
function mouseout() {
d3.select(this).select("circle").transition()
.duration(750)
.attr("r", 8);
d3.select(this).select("text")
.attr("font-size","12px")
.style("font-weight", "normal");
};
}) // end json
Here's someone else's solution:
This network graph uses the D3 force layout to draw nodes and links, but instead of using d3.force() to find the best node positions, we draw an invisible arc and evenly places nodes along the circumference.
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
<style>
line.node-link, path.node-link {
fill: none;
stroke: black
}
circle.node {
fill: white;
stroke: black
}
circle.node+text {
text-anchor: middle;
}
text {
font-family: sans-serif;
pointer-events: none;
}
</style>
</head>
<body>
<script type="text/javascript">
// number of random nodes (gets crowded at >25 unless you change node diameter)
var num = 20;
// returns random int between 0 and num
function getRandomInt() {return Math.floor(Math.random() * (num));}
// nodes returns a [list] of {id: 1, fixed:true}
var nodes = d3.range(num).map(function(d) { return {id: d}; });
// links returns a [list] of {source: 0, target: 1} (values refer to indicies of nodes)
var links = d3.range(num).map(function(d) { return {source: getRandomInt(), target: getRandomInt()}; });
var width = 500,
height = 500;
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.size([width, height]);
// evenly spaces nodes along arc
var circleCoord = function(node, index, num_nodes){
var circumference = circle.node().getTotalLength();
var pointAtLength = function(l){return circle.node().getPointAtLength(l)};
var sectionLength = (circumference)/num_nodes;
var position = sectionLength*index+sectionLength/2;
return pointAtLength(circumference-position)
}
// fades out lines that aren't connected to node d
var is_connected = function(d, opacity) {
lines.transition().style("stroke-opacity", function(o) {
return o.source === d || o.target === d ? 1 : opacity;
});
}
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// invisible circle for placing nodes
// it's actually two arcs so we can use the getPointAtLength() and getTotalLength() methods
var dim = width-80
var circle = svg.append("path")
.attr("d", "M 40, "+(dim/2+40)+" a "+dim/2+","+dim/2+" 0 1,0 "+dim+",0 a "+dim/2+","+dim/2+" 0 1,0 "+dim*-1+",0")
.style("fill", "#f5f5f5");
force.start();
// set coordinates for container nodes
nodes.forEach(function(n, i) {
var coord = circleCoord(n, i, nodes.length)
n.x = coord.x
n.y = coord.y
});
// use this one for straight line links...
// var lines = svg.selectAll("line.node-link")
// .data(links).enter().append("line")
// .attr("class", "node-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; });
// ...or use this one for curved line links
var lines = svg.selectAll("path.node-link")
.data(links).enter().append("path")
.attr("class", "node-link")
.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" +
d.source.x + "," +
d.source.y + "A" +
dr + "," + dr + " 0 0,1 " +
d.target.x + "," +
d.target.y;
});
var gnodes = svg.selectAll('g.gnode')
.data(nodes).enter().append('g')
.attr("transform", function(d) {
return "translate("+d.x+","+d.y+")"
})
.classed('gnode', true);
var node = gnodes.append("circle")
.attr("r", 25)
.attr("class", "node")
.on("mouseenter", function(d) {
is_connected(d, 0.1)
node.transition().duration(100).attr("r", 25)
d3.select(this).transition().duration(100).attr("r", 30)
})
.on("mouseleave", function(d) {
node.transition().duration(100).attr("r", 25);
is_connected(d, 1);
});
var labels = gnodes.append("text")
.attr("dy", 4)
.text(function(d){return d.id})
</script>
</body>
</html>

Trying build graph using d3.js

I am a newbie to d3 and trying to do a graph layout.
var w = 1000;
var h = 500;
var dataset = {
nodes: [{
name: 'Aden'
}, {
name: 'Bob'
}, {
name: 'Sue'
}],
edges: [{
source: 0,
target: 1
}, {
source: 1,
target: 2
}]
};
var svg = d3.select("body")
.append("svg")
.attr("height", h)
.attr("width", w);
var force = d3.layout.force()
.nodes(dataset.nodes)
.links(dataset.edges)
.size([w, h])
.linkDistance([50])
.start();
var nodes = svg.selectAll("circle")
.data(dataset.nodes)
.enter()
.append("circle")
.attr("r", 10)
.style("fill", "red")
.call(force.drag);
var edges = svg.selectAll("line")
.data(dataset.edges)
.enter()
.append("line")
.style("stroke", "#ccc")
.style("stroke-width", 1);
My fiddle is in : http://jsfiddle.net/abhimita/MnX23/
I don't see any graph but couldn't figure out what I am doing incorrectly. Any help will be really appreciated.
1.you neet to set cx and cy of circle to position the circle
2.you need to set x1 y1, x2 y2 of line to position line
3.if you need active you need to listen to tick event of force layout
var w = 300;
var h = 300;
var dataset = {
nodes: [{
name: 'Aden'
}, {
name: 'Bob'
}, {
name: 'Sue'
}],
edges: [{
source: 0,
target: 1
}, {
source: 1,
target: 2
}]
};
var svg = d3.select("body")
.append("svg")
.attr("height", h)
.attr("width", w);
var force = d3.layout.force()
.nodes(dataset.nodes)
.links(dataset.edges)
.size([w, h])
.on("tick", tick) // listener tick to listen position change
.linkDistance([50])
.start();
var nodes = svg.selectAll("circle")
.data(dataset.nodes)
.enter()
.append("circle")
.attr("r", 10)
// set cx cy of circle to position the circle
.attr("cx", function (d) {return d.x; })
.attr("cy", function (d) { return d.y; })
.style("fill", "red")
.call(force.drag);
var edges = svg.selectAll("line")
.data(dataset.edges)
.enter()
.append("line")
// set x1, y1, x2, y2 to position the line
.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;
})
.style("stroke", "#ccc")
.style("stroke-width", 1);
// make it actively
function tick(e) {
edges.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; });
nodes.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
demo update: http://jsfiddle.net/MnX23/3/
In circle you have to mention the cx and cy attributes and line x1,y1,x2,y2 attributes
The x1 attribute defines the start of the line on the x-axis
The y1 attribute defines the start of the line on the y-axis
The x2 attribute defines the end of the line on the x-axis
The y2 attribute defines the end of the line on the y-axis
Try this code:
DEMO
var w = 1000;
var h = 500;
var dataset = {
nodes: [{
name: 'Aden'
}, {
name: 'Bob'
}, {
name: 'Sue'
}],
edges: [{
source: 0,
target: 1
}, {
source: 1,
target: 2
}]
};
var svg = d3.select("body")
.append("svg")
.attr("height", h)
.attr("width", w);
var force = d3.layout.force()
.nodes(dataset.nodes)
.links(dataset.edges)
.size([w, h])
.linkDistance([50])
.start();
var nodes = svg.selectAll("circle")
.data(dataset.nodes)
.enter()
.append("circle")
.attr("r", 10)
.style("fill", "red")
.call(force.drag);
var edges = svg.selectAll("line")
.data(dataset.edges)
.enter()
.append("line")
.style("stroke", "#ccc")
.style("stroke-width", 1);
force.on("tick", function() {
edges.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; });
nodes.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});

Node drag not working on iPad

I would like to drag node and drag canvas (svg element)
On a desktop browser, it works fine, but on an iPad it only drags the canvas; node dragging is not working. Where did I go wrong?
My source code:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
}
</style>
<body>
<script src="d3.js"></script>
<script>
var view_w = width = 960,
view_h = height = 500,
view_y = 0,
view_x = 0;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", view_x+" "+view_y+" "+view_w+" "+view_h);
var canvasdrag = d3.behavior.drag().on("drag", function(d){
view_x -= d3.event.dx;
view_y -= d3.event.dy;
//change svg position
svg.attr("translate", view_x + " " + view_y);
//change viewBox start position
svg.attr("viewBox", view_x+" "+view_y+" "+view_w+" "+view_h);
});
svg.call(canvasdrag);
d3.json("./sample.json", function(error, graph) {
graph.links.forEach(function(d) {
d.source = graph.nodes[d.source];
d.target = graph.nodes[d.target];
});
var link = svg.append("g")
.attr("class", "link")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.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; });
var node = svg.append("g")
.attr("class", "node")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 6)
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("drag", function(d) {
d.x = d3.event.x, d.y = d3.event.y;
d3.select(this).attr("cx", d.x).attr("cy", d.y);
link.filter(function(l) { return l.source === d; }).attr("x1", d.x).attr("y1", d.y);
link.filter(function(l) { return l.target === d; }).attr("x2", d.x).attr("y2", d.y);
}));
});
</script>
[sample.json]
{"nodes":[{"x":444,"y":275},{"x":378,"y":324},{"x":478,"y":278},{"x":471,"y":256},{"x":382,"y":269},{"x":371,"y":247},{"x":359,"y":276},{"x":364,"y":302},{"x":400,"y":330},{"x":388,"y":298},{"x":524,"y":296},{"x":570,"y":243},{"x":552,"y":159},{"x":502,"y":287},{"x":511,"y":313},{"x":513,"y":265},{"x":602,"y":132},{"x":610,"y":90},{"x":592,"y":91},{"x":575,"y":89},{"x":607,"y":73},{"x":591,"y":68},{"x":574,"y":73},{"x":589,"y":149},{"x":620,"y":205},{"x":621,"y":230},{"x":589,"y":234},{"x":602,"y":223},{"x":548,"y":188},{"x":532,"y":196},{"x":548,"y":114},{"x":575,"y":174},{"x":497,"y":250},{"x":576,"y":196},{"x":504,"y":201},{"x":494,"y":186},{"x":482,"y":199},{"x":505,"y":219},{"x":486,"y":216},{"x":590,"y":306},{"x":677,"y":169},{"x":657,"y":258},{"x":667,"y":205},{"x":552,"y":227},{"x":518,"y":173},{"x":473,"y":125},{"x":796,"y":260},{"x":731,"y":272},{"x":642,"y":288},{"x":576,"y":269},{"x":605,"y":187},{"x":559,"y":289},{"x":544,"y":356},{"x":505,"y":365},{"x":579,"y":289},{"x":619,"y":282},{"x":574,"y":329},{"x":664,"y":306},{"x":627,"y":304},{"x":643,"y":327},{"x":664,"y":348},{"x":665,"y":327},{"x":653,"y":317},{"x":650,"y":338},{"x":622,"y":321},{"x":633,"y":338},{"x":647,"y":357},{"x":718,"y":362},{"x":636,"y":240},{"x":640,"y":227},{"x":617,"y":249},{"x":631,"y":254},{"x":566,"y":213},{"x":713,"y":322},{"x":716,"y":298},{"x":666,"y":241},{"x":627,"y":355}],"links":[{"source":1,"target":0},{"source":2,"target":0},{"source":3,"target":0},{"source":3,"target":2},{"source":4,"target":0},{"source":5,"target":0},{"source":6,"target":0},{"source":7,"target":0},{"source":8,"target":0},{"source":9,"target":0},{"source":11,"target":10},{"source":11,"target":3},{"source":11,"target":2},{"source":11,"target":0},{"source":12,"target":11},{"source":13,"target":11},{"source":14,"target":11},{"source":15,"target":11},{"source":17,"target":16},{"source":18,"target":16},{"source":18,"target":17},{"source":19,"target":16},{"source":19,"target":17},{"source":19,"target":18},{"source":20,"target":16},{"source":20,"target":17},{"source":20,"target":18},{"source":20,"target":19},{"source":21,"target":16},{"source":21,"target":17},{"source":21,"target":18},{"source":21,"target":19},{"source":21,"target":20},{"source":22,"target":16},{"source":22,"target":17},{"source":22,"target":18},{"source":22,"target":19},{"source":22,"target":20},{"source":22,"target":21},{"source":23,"target":16},{"source":23,"target":17},{"source":23,"target":18},{"source":23,"target":19},{"source":23,"target":20},{"source":23,"target":21},{"source":23,"target":22},{"source":23,"target":12},{"source":23,"target":11},{"source":24,"target":23},{"source":24,"target":11},{"source":25,"target":24},{"source":25,"target":23},{"source":25,"target":11},{"source":26,"target":24},{"source":26,"target":11},{"source":26,"target":16},{"source":26,"target":25},{"source":27,"target":11},{"source":27,"target":23},{"source":27,"target":25},{"source":27,"target":24},{"source":27,"target":26},{"source":28,"target":11},{"source":28,"target":27},{"source":29,"target":23},{"source":29,"target":27},{"source":29,"target":11},{"source":30,"target":23},{"source":31,"target":30},{"source":31,"target":11},{"source":31,"target":23},{"source":31,"target":27},{"source":32,"target":11},{"source":33,"target":11},{"source":33,"target":27},{"source":34,"target":11},{"source":34,"target":29},{"source":35,"target":11},{"source":35,"target":34},{"source":35,"target":29},{"source":36,"target":34},{"source":36,"target":35},{"source":36,"target":11},{"source":36,"target":29},{"source":37,"target":34},{"source":37,"target":35},{"source":37,"target":36},{"source":37,"target":11},{"source":37,"target":29},{"source":38,"target":34},{"source":38,"target":35},{"source":38,"target":36},{"source":38,"target":37},{"source":38,"target":11},{"source":38,"target":29},{"source":39,"target":25},{"source":40,"target":25},{"source":41,"target":24},{"source":41,"target":25},{"source":42,"target":41},{"source":42,"target":25},{"source":42,"target":24},{"source":43,"target":11},{"source":43,"target":26},{"source":43,"target":27},{"source":44,"target":28},{"source":44,"target":11},{"source":45,"target":28},{"source":47,"target":46},{"source":48,"target":47},{"source":48,"target":25},{"source":48,"target":27},{"source":48,"target":11},{"source":49,"target":26},{"source":49,"target":11},{"source":50,"target":49},{"source":50,"target":24},{"source":51,"target":49},{"source":51,"target":26},{"source":51,"target":11},{"source":52,"target":51},{"source":52,"target":39},{"source":53,"target":51},{"source":54,"target":51},{"source":54,"target":49},{"source":54,"target":26},{"source":55,"target":51},{"source":55,"target":49},{"source":55,"target":39},{"source":55,"target":54},{"source":55,"target":26},{"source":55,"target":11},{"source":55,"target":16},{"source":55,"target":25},{"source":55,"target":41},{"source":55,"target":48},{"source":56,"target":49},{"source":56,"target":55},{"source":57,"target":55},{"source":57,"target":41},{"source":57,"target":48},{"source":58,"target":55},{"source":58,"target":48},{"source":58,"target":27},{"source":58,"target":57},{"source":58,"target":11},{"source":59,"target":58},{"source":59,"target":55},{"source":59,"target":48},{"source":59,"target":57},{"source":60,"target":48},{"source":60,"target":58},{"source":60,"target":59},{"source":61,"target":48},{"source":61,"target":58},{"source":61,"target":60},{"source":61,"target":59},{"source":61,"target":57},{"source":61,"target":55},{"source":62,"target":55},{"source":62,"target":58},{"source":62,"target":59},{"source":62,"target":48},{"source":62,"target":57},{"source":62,"target":41},{"source":62,"target":61},{"source":62,"target":60},{"source":63,"target":59},{"source":63,"target":48},{"source":63,"target":62},{"source":63,"target":57},{"source":63,"target":58},{"source":63,"target":61},{"source":63,"target":60},{"source":63,"target":55},{"source":64,"target":55},{"source":64,"target":62},{"source":64,"target":48},{"source":64,"target":63},{"source":64,"target":58},{"source":64,"target":61},{"source":64,"target":60},{"source":64,"target":59},{"source":64,"target":57},{"source":64,"target":11},{"source":65,"target":63},{"source":65,"target":64},{"source":65,"target":48},{"source":65,"target":62},{"source":65,"target":58},{"source":65,"target":61},{"source":65,"target":60},{"source":65,"target":59},{"source":65,"target":57},{"source":65,"target":55},{"source":66,"target":64},{"source":66,"target":58},{"source":66,"target":59},{"source":66,"target":62},{"source":66,"target":65},{"source":66,"target":48},{"source":66,"target":63},{"source":66,"target":61},{"source":66,"target":60},{"source":67,"target":57},{"source":68,"target":25},{"source":68,"target":11},{"source":68,"target":24},{"source":68,"target":27},{"source":68,"target":48},{"source":68,"target":41},{"source":69,"target":25},{"source":69,"target":68},{"source":69,"target":11},{"source":69,"target":24},{"source":69,"target":27},{"source":69,"target":48},{"source":69,"target":41},{"source":70,"target":25},{"source":70,"target":69},{"source":70,"target":68},{"source":70,"target":11},{"source":70,"target":24},{"source":70,"target":27},{"source":70,"target":41},{"source":70,"target":58},{"source":71,"target":27},{"source":71,"target":69},{"source":71,"target":68},{"source":71,"target":70},{"source":71,"target":11},{"source":71,"target":48},{"source":71,"target":41},{"source":71,"target":25},{"source":72,"target":26},{"source":72,"target":27},{"source":72,"target":11},{"source":73,"target":48},{"source":74,"target":48},{"source":74,"target":73},{"source":75,"target":69},{"source":75,"target":68},{"source":75,"target":25},{"source":75,"target":48},{"source":75,"target":41},{"source":75,"target":70},{"source":75,"target":71},{"source":76,"target":64},{"source":76,"target":65},{"source":76,"target":66},{"source":76,"target":63},{"source":76,"target":62},{"source":76,"target":48},{"source":76,"target":58}]}
I’m using d3.js version 788855b4a4141fab9554513976dcc50004c76489.

d3.js force layout increase linkDistance

How to increase linkDistance without affecting the node alignment,
example: http://mbostock.github.com/d3/talk/20110921/force.html
when I try to increase the circle radius and linkDistance
the it collapse
<script type="text/javascript">
var w = 1280,
h = 800,
z = d3.scale.category20c();
var force = d3.layout.force()
.size([w, h]);
var svg = d3.select("#chart").append("svg:svg")
.attr("width", w)
.attr("height", h);
svg.append("svg:rect")
.attr("width", w)
.attr("height", h);
d3.json("flare.json", function(root) {
var nodes = flatten(root),
links = d3.layout.tree().links(nodes);
force
.nodes(nodes)
.links(links)
.start();
var link = svg.selectAll("line")
.data(links)
.enter().insert("svg:line")
.style("stroke", "#999")
.style("stroke-width", "1px");
var node = svg.selectAll("circle.node")
.data(nodes)
.enter().append("svg:circle")
.attr("r", 4.5)
.style("fill", function(d) { return z(d.parent && d.parent.name); })
.style("stroke", "#000")
.call(force.drag);
force.on("tick", function(e) {
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; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
});
function flatten(root) {
var nodes = [];
function recurse(node, depth) {
if (node.children) {
node.children.forEach(function(child) {
child.parent = node;
recurse(child, depth + 1);
});
}
node.depth = depth;
nodes.push(node);
}
recurse(root, 1);
return nodes;
}
</script>
Play around with the .charge parameter. It defines how much the nodes repel each other.

Categories

Resources