Skip to content

Instantly share code, notes, and snippets.

@veltman
Created November 19, 2013 16:09
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 veltman/7547765 to your computer and use it in GitHub Desktop.
Save veltman/7547765 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>For Aly</title>
<meta charset="utf-8">
<style>
body {
font: 14px sans-serif;
}
path {
stroke-width: 2px;
fill: none;
}
path.Japan {
stroke: tomato;
}
path.United_Kingdom {
stroke: steelblue;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var width = 600,
height = 400,
margin = 30;
var x = d3.scale.linear().domain([1750,1930]).range([margin,width-margin]);
var y = d3.scale.linear().domain([0,71]).range([height-margin,margin]);
//Create the SVG
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
var xAxis = d3.svg.axis()
.tickFormat(d3.format("d"))
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
//Create the x axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height-margin) + ")")
.call(xAxis);
//Create the y axis
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + margin + ")")
.call(yAxis);
//Generate a line from an array of points of format:
//{year: 1910, count: 50}
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.year); })
.y(function(d) { return y(d.count); });
//Get the data
d3.tsv("aly.tsv",function(err,tsv) {
var lines = {};
//For each column
for (var column in tsv[0]) {
//Skip the year
if (column == "year") continue;
//For each column besides year, add an array of points to lines
lines[column] = tsv.map(function(d){
return {"year": d.year, "count": d[column]};
}).filter(function(d){
//Filter out empty ones
return d.count.length;
});
}
//Create the paths, use the entries for the data
//Each item in the entries will be
//{key: "COUNTRY NAME", value: [ARRAY OF OBJECTS, EACH WITH A "year" AND "count" property]}
svg.append("g").selectAll("path")
.data(d3.entries(lines))
.enter()
.append("path")
.attr("class",function(d){
//This will be "Japan" or "United_Kingdom"
return d.key.replace(" ","_");
})
.attr("d",function(d) {
//Generate the line
return line(d.value);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment