Skip to content

Instantly share code, notes, and snippets.

@hyponymous
Created September 20, 2013 23:35
Show Gist options
  • Save hyponymous/6645319 to your computer and use it in GitHub Desktop.
Save hyponymous/6645319 to your computer and use it in GitHub Desktop.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title></title>
<style type="text/css">
.chart rect
{
fill: steelblue;
stroke: white;
}
</style>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
<!--
function clamp(val, low, hi)
{
return Math.min(hi, Math.max(low, val));
}
var t = 0;
var v = 50;
function next()
{
return {
time: ++t,
value: v = Math.round(clamp(v + 10 * (Math.random() - 0.5), 0, 100))
};
}
$(window).load(function ()
{
var data = d3.range(40).map(next);
var w = 20;
var h = 80;
var x = d3.scale.linear().domain([0, 1]).range([0, w]);
var y = d3.scale.linear().domain([0, 100]).rangeRound([0, h]);
function setX(dIndex)
{
return function (d, i) { return x(i + dIndex) - 0.5; };
}
var chart = d3.select("body").append("svg:svg")
.attr("class", "chart")
.attr("width", w * data.length - 1)
.attr("height", h)
;
var group = chart.append("g");
group.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", setX(0))
.attr("y", function (d) { return h - y(d.value) - 0.5; })
.attr("width", w)
.attr("height", function (d) { return y(d.value); })
;
chart.append("line")
.attr("x1", 0)
.attr("x2", w * data.length)
.attr("y1", h - 0.5)
.attr("y2", h - 0.5)
.style("stroke", "#f09")
;
function redraw()
{
var rects = group.selectAll("rect")
.data(data, function (d) { return d.time; })
;
var duration = 500;
rects.enter()
.insert("rect", "line")
.attr("x", setX(1))
.attr("y", function (d) { return h - y(d.value) - 0.5; })
.attr("width", w)
.attr("height", function (d) { return y(d.value); })
.transition()
.duration(duration)
.attr("x", setX(0))
;
rects.transition()
.duration(duration)
.attr("x", setX(0))
;
rects.exit()
.transition()
.duration(duration)
.attr("x", setX(-1))
.remove()
;
}
setInterval(function ()
{
data.shift();
data.push(next());
console.log(data[0].value)
redraw();
}, 2000);
});
// -->
</script>
</head>
<body>
<div id="chart">
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment