Skip to content

Instantly share code, notes, and snippets.

@eesur
Created June 7, 2016 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eesur/6130690583e525d61f44abab61900db4 to your computer and use it in GitHub Desktop.
Save eesur/6130690583e525d61f44abab61900db4 to your computer and use it in GitHub Desktop.
d3js | circles update with force layout

based of this really nice example: pusher.com/dynamic-graphs-with-d3-js/

data generated in this format, looping over red, green, blue and incrementing the id:

render([{
    id: 1,
    color: 'red'
}, {
    id: 2,
    color: 'green'
}, {
    id: 3,
    color: 'blue'
}]);
<!DOCTYPE html>
<meta charset="utf-8">
<!-- http://clrs.cc/ -->
<link href="//s3-us-west-2.amazonaws.com/colors-css/2.2.0/colors.min.css" rel="stylesheet">
<style>
body { background: #130C0E; }
</style>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<!-- d3 code -->
<script src="script-compiled.js" charset="utf-8"></script>
'use strict';
var w = window.innerWidth;
var h = window.innerHeight;
// store generated data
var data = [];
var svg = d3.select('body').append('svg').attr('width', w).attr('height', h);
var circle = svg.selectAll('circle');
var force = d3.layout.force().size([w, h]).on('tick', function () {
circle.attr('cx', function (d) {
return d.x;
}).attr('cy', function (d) {
return d.y;
});
});
var render = function render(data) {
circle = circle.data(data, function (d) {
return d.id;
});
circle.enter().append('circle').attr('fill', function (d) {
return d.color;
}).attr('r', 12).call(force.drag);
circle.exit().transition().attr('r', 0).remove();
force.nodes(data).start();
};
// generate some data
function update() {
var n = 0;
var c = ['red', 'green', 'blue'];
return function () {
data.push({
id: n,
color: c[n % 3]
});
console.log(data);
render(data);
n++;
};
}
// update every second
// note: calling as update()(); (higher order function)
setInterval(update(), 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment