Skip to content

Instantly share code, notes, and snippets.

@mattsacks
Created June 7, 2012 02:59
Show Gist options
  • Save mattsacks/2886280 to your computer and use it in GitHub Desktop.
Save mattsacks/2886280 to your computer and use it in GitHub Desktop.
N-Point Comparison to 15-Point
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>D3 Multiple-Point Line Transition</title>
<style type='text/css'>
/*<![CDATA[*/
path {
stroke: black;
stroke-width: 2px;
fill: transparent;
}
hgroup * {
position: absolute;
z-index: -1;
font-family: 'Helvetica Neue', Helvetica, sans-serif;
}
h1 {
font-weight: 100;
}
h1:nth-of-type(1) {
top: 75px;
}
h4 {
font-size: 13px;
font-weight: 400;
top: 120px;
}
h1:nth-of-type(2) {
top: 350px;
}
/*]]>*/
</style>
</head>
<body>
<hgroup>
<h1>N-Point Line</h1>
<h4>(between 8 and 15)</h4>
<h1>15-Point Line</h1>
</hgroup>
<script src='http://d3js.org/d3.v2.js?2.9.1'></script>
<script type='text/javascript'>
//<![CDATA[
paths = false;
var update = function(type) {
if (type === 'normal') {
var n = 15,
range = [500, 251];
} else { // 'multi'
var n = Math.floor(Math.random() * (15 - 8 + 1)) + 8,
range = [249, 0]
}
data = d3.range(n).map(d3.random.normal(0, 0.2));
x = d3.scale.linear()
.domain([0, n-1])
.range([0, 960]);
y = d3.scale.linear()
.domain([d3.min(data), d3.max(data)])
.range(range);
line = d3.svg.line()
.interpolate('basis')
// x loses scope for some reason, this is a cheap fix
.x(function(d,i) { return x.domain([0, n-1])(i); })
.y(y);
if (window.paths) {
window[type+'Path']
.data([data])
.transition()
.duration(200)
.attr('d', line);
}
}
var create = function(type) {
update(type);
return svg.selectAll('#'+type)
.data([data])
.enter()
.append('svg:path')
.attr('id', type)
.attr('d', line);
}
var svg = d3.select('body').append('svg')
.attr('width', 960)
.attr('height', 500);
onInterval = function() {
if (!window.paths) {
window.multiPath = create('multi');
window.normalPath = create('normal');
window.paths = true;
} else {
update('multi');
update('normal');
}
};
setInterval(onInterval, 750);
//]]>
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment