Created
November 28, 2015 00:25
-
-
Save d3byex/da683ed91ea9b9c031c0 to your computer and use it in GitHub Desktop.
D3byEX 11.5: Sticky Nodes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta name="description" content="D3byEX 11.5"> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> | |
<script> | |
var url = 'https://gist.githubusercontent.com/d3byex/5a8267f90a0d215fcb3e/raw/b53d20a8a6a82fd8bab2c03e0ec5a96262b5c8da/uni_network.json'; | |
d3.json(url, function (error, data) { | |
var width = 960, height = 500; | |
var svg = d3.select('body') | |
.append('svg') | |
.attr({ | |
width: width, | |
height: height | |
}); | |
var force = d3.layout.force() | |
.size([width, height]) | |
.charge(-200) | |
.linkDistance(1) | |
.charge(-4000) | |
.nodes(data.nodes) | |
.links(data.edges) | |
.start(); | |
var edges = svg.selectAll('line') | |
.data(data.edges) | |
.enter() | |
.append('line') | |
.style('stroke', '#ccc') | |
.style('stroke-width', 1); | |
var nodes = svg.selectAll('g') | |
.data(data.nodes) | |
.enter() | |
.append('g') | |
.call(force.drag); | |
var colors = d3.scale.category20(); | |
nodes.append('circle') | |
.attr('r', 10) | |
.attr({ | |
r: 10, | |
fill: function (d, i) { | |
return colors(i); | |
}, | |
stroke: 'black', | |
'stroke-width': 0 | |
}) | |
.call(force.drag() | |
.on("dragstart", function (d) { | |
d.fixed = true; | |
d3.select(this).attr('stroke-width', 3); | |
})) | |
.on('dblclick', function (d) { | |
d.fixed = false; | |
d3.select(this).attr('stroke-width', 0); | |
}); | |
nodes.append('text') | |
.attr({ | |
dx: 12, | |
dy: '.35em', | |
'pointer-events': 'none' | |
}) | |
.style('font', '10px sans-serif') | |
.text(function (d) { return d.name }); | |
force.on('tick', function () { | |
edges.each(function (d) { | |
d3.select(this).attr({ | |
x1: d.source.x, | |
y1: d.source.y, | |
x2: d.target.x, | |
y2: d.target.y | |
}); | |
}); | |
nodes.attr('transform', function (d) { | |
return 'translate(' + d.x + ',' + d.y + ')'; | |
}); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment