|
/* Remember: Use four-space indents. |
|
* However, use two-space indents for operations that change the selection. |
|
* For more information, see: |
|
* https://bost.ocks.org/mike/d3/workshop/#35 |
|
*/ |
|
var svg = d3.select("svg"), |
|
margin = {top: 20, right: 20, bottom: 20, left: 150}, |
|
width = +svg.attr("width") - margin.left - margin.right, |
|
height = +svg.attr("height") - margin.top - margin.bottom; |
|
|
|
var g = svg.append("g") |
|
.attr("transform", translate(margin.left, margin.top)); |
|
|
|
d3.csv("emissions.csv", row, function (error, emissions) { |
|
var byCountry = d3.nest() |
|
.key(function (d) { return d.country_name; }) |
|
.sortValues(function (a, b) { return d3.ascending(a.year, b.year); }) |
|
.map(emissions); |
|
|
|
var x = d3.scaleTime() |
|
.domain(d3.extent(emissions, function (d) { return d.year; })) |
|
.range([0, width]) |
|
.nice(); |
|
|
|
// Create a global y scale for all multiples. |
|
var y0 = d3.scaleBand() |
|
.domain(byCountry.keys().sort(d3.ascending)) |
|
.range([0, height]) |
|
.paddingInner(0.2); |
|
|
|
var line = d3.local(); |
|
|
|
var multiple = g.append("g").selectAll(".multiple") |
|
.data(byCountry.entries()) |
|
.enter().append("g") // Each multiple has its own local origin. |
|
.attr("transform", function (d) { return translate(0, y0(d.key)); }) |
|
.attr("class", "multiple") |
|
.each(localMultiple); |
|
|
|
multiple.append("rect") |
|
.attr("width", width) |
|
.attr("height", y0.bandwidth()) |
|
.attr("fill", "#f0f0f0"); |
|
|
|
multiple.append("path") |
|
.attr("d", function (d) { return line.get(this)(d.value); }) |
|
.attr("fill", "none") |
|
.attr("stroke", "#de2d26") |
|
.attr("stroke-width", 0.5); |
|
|
|
g.append("g") |
|
.call(d3.axisTop(x)) |
|
.call(customAxis); |
|
|
|
g.append("g") |
|
.call(d3.axisLeft(y0)) |
|
.call(customAxis); |
|
|
|
function localMultiple(d) { |
|
// Create a local y scale and local line generator for each multiple. |
|
// For more information, see: |
|
// https://bl.ocks.org/mbostock/e1192fe405703d8321a5187350910e08 |
|
var y1 = d3.scaleLinear() |
|
.domain(d3.extent(d.value, function (d) { return d.emissions; })) |
|
.range([y0.bandwidth(), 0]); |
|
|
|
var _line = d3.line() |
|
.x(function (d) { return x(d.year); }) |
|
.y(function (d) { return y1(d.emissions); }); |
|
|
|
line.set(this, _line); |
|
} |
|
}); |
|
|
|
function translate(x, y) { |
|
return "translate(" + x + "," + y + ")"; |
|
} |
|
|
|
function row(d) { |
|
d.year = d3.utcParse("%Y")(d.year) |
|
d.emissions = +d.emissions; |
|
return d; |
|
} |
|
|
|
function customAxis(g) { |
|
g.selectAll(".domain").remove(); |
|
g.selectAll(".tick line").remove(); |
|
} |