Skip to content

Instantly share code, notes, and snippets.

@zoopoetics
Last active December 29, 2015 07:09
Show Gist options
  • Save zoopoetics/7634466 to your computer and use it in GitHub Desktop.
Save zoopoetics/7634466 to your computer and use it in GitHub Desktop.
Rendering Timeseries Data with D3
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
// Data
var data = [],
timestamp = new Date();
for (var i = 0; i < 24; i++) {
var hours = timestamp.getHours() + 1
timestamp.setHours(hours);
data.push({
timestamp: new Date(timestamp),
value: Math.random()
});
}
// Dimensions
var margin = {
top: 0,
right: 0,
bottom: 0,
left: 0
},
width = 960,
height = 500;
// Domains
var domainX = d3.extent(data, function(datum) {
return datum.timestamp;
});
var domainY = d3.extent(data, function(datum) {
return datum.value;
});
// Ranges
var rangeX = [0, width],
rangeY = [height, 0];
// Scales
var scaleX = d3.time.scale()
.domain(domainX)
.range(rangeX);
var scaleY = d3.scale.linear()
.domain(domainY)
.range(rangeY);
// Shape generators
var line = d3.svg.line()
.x(function(datum) {
return scaleX(datum.timestamp);
})
.y(function(datum) {
return scaleY(datum.value);
});
// Append an SVG element
var svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height);
// Append path
var path = svg.append('path')
.datum(data)
.attr('class', 'line')
.attr('d', line)
.style('fill', 'none')
.style('stroke', '#FB5050')
.style('stroke-width', '3px');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment