Skip to content

Instantly share code, notes, and snippets.

@joews
Created June 7, 2014 16:22
Show Gist options
  • Save joews/bb871da936bbb1b1c9ac to your computer and use it in GitHub Desktop.
Save joews/bb871da936bbb1b1c9ac to your computer and use it in GitHub Desktop.
d3 multi-series scatter plot with series and data point transitions
<!DOCTYPE html>
<html>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var min = 0,
max = 10;
// Create a one dimensional array of random [x,y] pairs
function getSeries() {
var length = randomInt(4, 8),
series = [];
for(var i = 0; i < length; ++i) {
series.push([randomInt(min, max), randomInt(min, max)]);
}
return series;
}
// Create an array containing a random number of series arrays
// I am aware that "serieses" is not a word.
function getSerieses() {
var n = randomInt(1,4),
serieses = [];
for(var i = 0; i < n; ++i) {
serieses.push(getSeries());
}
return serieses;
}
var margin = 20,
outerWidth = 500,
outerHeight = 500,
width = outerWidth - 2 * margin,
height = outerWidth - 2 * margin;
var svg = d3.select("body").append("svg")
.attr("width", outerWidth)
.attr("height", outerHeight)
.append("g")
.attr("transform", "translate(" + margin + "," + margin + ")");
var chart = svg.append('g').attr('class', 'chart');
var x = d3.scale.linear()
.range([0, width])
.domain([0, 10]);
var y = d3.scale.linear()
.range([0, height])
.domain([0, 10]);
var z = d3.scale.category10();
function update(serieses) {
var series = chart.selectAll("g")
.data(serieses);
series.enter()
.append('g');
series.exit()
.transition()
.duration(1000)
.style('opacity', 0)
.remove();
var circles = series.selectAll('circle')
.data(function(d, i) { return d })
// update
circles
.transition()
.duration(1000)
.attr('cx', function(d) { return x(d[0]) })
.attr('cy', function(d) { return y(d[1]) })
circles.enter()
.append('circle')
.attr('cx', function(d) { return x(d[0]) })
.attr('cy', function(d) { return y(d[1]) })
.attr('r', 10)
.attr('fill', function(d, i, seriesNum) { return z(seriesNum) })
.style('opacity', 0)
.transition()
.duration(1000)
.style('opacity', 1);
circles.exit()
.transition()
.duration(1000)
.style('opacity', 0)
.remove();
}
update(getSerieses());
setInterval(function() { update(getSerieses()) }, 2000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment