Skip to content

Instantly share code, notes, and snippets.

@exupero
Last active December 20, 2015 19:58
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 exupero/6186864 to your computer and use it in GitHub Desktop.
Save exupero/6186864 to your computer and use it in GitHub Desktop.
Uncertain Future Projection

A line graph with a projected future that waves to indicate uncertainty in the projection.

<!DOCTYPE html>
<meta http-equiv="content-type" content="text/html; charset=UTF8">
<style>
.line {
fill: none;
stroke: steelblue;
stroke-width: 3;
}
.projected {
stroke-dasharray: 5 3;
}
</style>
<body>
<script src=http://d3js.org/d3.v3.min.js></script>
<script>
var data = [],
y = Math.random();
for (var x = 0; x <= 12; x++) {
y = y + Math.random() - 0.5;
data.push({x: x, y: y});
}
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(10, 10)");
var x = d3.scale.linear()
.domain([0, 12])
.range([0, width - 20]);
var y = d3.scale.linear()
.domain(d3.extent(data, function(d) { return d.y }))
.range([height - 20, 0]);
var line = d3.svg.line()
.x(function(d) { return x(d.x) })
.y(function(d) { return y(d.y) });
svg.append("path")
.datum(data.slice(0, 7))
.attr("class", "line")
.attr("d", line);
var projectedData = data.slice(6);
var projected = svg.append("path")
.datum(projectedData)
.attr("class", "line projected")
.attr("d", line);
var t = 0;
setInterval(function() {
t += 0.15;
for (var i = 1; i < projectedData.length; i++) {
var cur = projectedData[i],
amplitude = i + 0.5 * Math.random(),
len = projectedData.length,
phaseShift = 4 * (len - i) / len;
projectedData[i] = {x: cur.x, y: data[cur.x].y + amplitude * Math.sin(t + phaseShift)};
}
projected.transition()
.duration(1000)
.ease("quad")
.attr("d", line);
}, 100);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment