Skip to content

Instantly share code, notes, and snippets.

@kforeman
Created September 8, 2011 13:00
Show Gist options
  • Save kforeman/1203335 to your computer and use it in GitHub Desktop.
Save kforeman/1203335 to your computer and use it in GitHub Desktop.
sliding line graph
<!DOCTYPE html>
<html>
<head>
<title>Line Chart</title>
<link type="text/css" rel="stylesheet" href="line.css"/>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<script type="text/javascript" src="line.js"></script>
</body>
</html>
.rule line {
stroke: #eee;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
(function () {
// Get a data set. 10 points.
function _getData () {
return d3.range(10).map(function(i) {return _getDataPoint(i)})
}
// Get a single point of data.
function _getDataPoint(i) {
return {x: i, y: (Math.random(i/3) + 1) / 2}
}
// Slide a point to the left.
function _slideDataPoint(datum, i) {
return {x: (i-1), y:datum.y}
}
// Add a data point to the right of the graph and slide the line to the
// left.
function addData() {
// Slap a new random point to the end of the data
data.push({x: 11, y:(Math.random(i/3) + 1) / 2});
// Adjust the X value for each point
for (i = 0; i < data.length; i++) {
data[i] = _slideDataPoint(data[i], i)
}
// redraw
}
// Set up the parameters of the chart object.
var width = 550,
height = 275,
x = d3.scale.linear().domain([0, 10]).range([0, width]),
y = d3.scale.linear().domain([0, 1]).range([height, 0]);
// Create the chart in its initial state
data = _getData();
vis = d3.select("body")
.append("svg:svg")
.attr("width", width)
.attr("height", height);
line_segments = vis.selectAll('line')
.data(d3.range(9))
.enter().append("svg:line")
.attr('class', 'line')
.attr('x1', function(d) { return x(data[d]['x']); })
.attr('x2', function(d) { return x(data[d+1]['x']); })
.attr('y1', function(d) { return y(data[d]['y']); })
.attr('y2', function(d) { return y(data[d+1]['y']); });
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment