Skip to content

Instantly share code, notes, and snippets.

@patrickberkeley
Forked from mbostock/.block
Last active August 29, 2015 13:56
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 patrickberkeley/9162034 to your computer and use it in GitHub Desktop.
Save patrickberkeley/9162034 to your computer and use it in GitHub Desktop.
{
"close": [
582.13,
583.98,
603.00,
607.70,
610.00,
560.28,
571.70,
572.98,
587.44,
608.34
],
"date": [
"02:30:00",
"02:45:00",
"03:00:00",
"03:15:00",
"03:30:00",
"03:45:00",
"04:00:00",
"04:15:00",
"04:30:00",
"04:45:00",
"05:00:00"
]
}
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// You have times instead of dates. So we need a time formatter.
var parseTime = d3.time.format("%H:%M:%S").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json("data.json", function(error, data) {
// 1) Zip the close value with their corresponding date/time
// Results in an array of arrays:
//
// [[582.13, "02:30:00"], [583.98, "02:45:00"], ...]
//
data = d3.zip(data.close, data.date).map(function(d) {
// 2) Format each close and date/time value so d3 understands what each represents.
close = +d[0];
// If your data source can't be changed at all, I'd rename `date` to `time` here.
date = parseTime(d[1]);
// 3) Return an object for each close and date/time pair.
return {close: close, date: date};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment