|
/* 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: 30, left: 80}, |
|
width = +svg.attr("width") - margin.left - margin.right, |
|
height = +svg.attr("height") - margin.top - margin.bottom, |
|
delay = 2000; |
|
|
|
var years = d3.range(2000, 2010), |
|
countries = ['Afghanistan', 'Bahamas', 'Cabo Verde', 'Denmark', 'Ecuador'], |
|
scores = countries.map(function () { return years.map(Math.random); }), |
|
data = d3.zip(countries, scores); |
|
|
|
var x = d3.scaleLinear() |
|
.range([0, width]); |
|
|
|
var y = d3.scalePoint() |
|
.domain(countries) |
|
.range([0, height]) |
|
.padding(0.5); |
|
|
|
var g = svg.append("g") |
|
.attr("transform", translate(margin.left, margin.top)); |
|
|
|
// The domain |
|
g.append("g").selectAll("line") |
|
.data(data) |
|
.enter().append("line") |
|
.attr("x1", x.range()[0]) |
|
.attr("x2", x.range()[1]) |
|
.attr("y1", function (d) { return y(d[0]); }) |
|
.attr("y2", function (d) { return y(d[0]); }) |
|
.attr("stroke", "black"); |
|
|
|
g.append("g") |
|
.attr("class", "year"); |
|
|
|
g.append("g") |
|
.attr("class", "circles"); |
|
|
|
g.append("g") |
|
.attr("transform", translate(0, height)) |
|
.attr("class", "x axis") |
|
.call(d3.axisBottom(x)) |
|
.call(customAxis); |
|
|
|
g.append("g") |
|
.attr("class", "y axis") |
|
.call(d3.axisLeft(y)) |
|
.call(customAxis); |
|
|
|
function update(elapsed) { |
|
var t = Math.floor(elapsed / delay) % years.length; |
|
|
|
var year = g.select(".year").selectAll("text") |
|
.data([years[t]]); |
|
|
|
year.enter().append("text") |
|
.attr("x", width - 10) |
|
.attr("y", 10) |
|
.attr("text-anchor", "end") |
|
.attr("font-size", 20) |
|
.attr("font-family", "sans-serif") |
|
.merge(year) |
|
.text(function (d) { return d; }); |
|
|
|
var circles = g.select(".circles").selectAll("circle") |
|
.data(data); |
|
|
|
circles.enter().append("circle") |
|
.attr("cx", function (d) { return x(d[1][t]); }) |
|
.attr("cy", function (d) { return y(d[0]); }) |
|
.attr("r", 6) |
|
.attr("fill", "white") |
|
.attr("stroke", "black") |
|
.attr("stroke-width", 2) |
|
.merge(circles).transition() |
|
.duration(delay / 2) |
|
.attr("cx", function (d) { return x(d[1][t]); }); |
|
} |
|
|
|
update(0); |
|
d3.interval(update, delay); |
|
|
|
function customAxis(g) { |
|
g.selectAll(".domain").remove(); |
|
g.selectAll(".tick line").remove(); |
|
} |
|
|
|
function translate(x, y) { |
|
return "translate(" + x + "," + y + ")"; |
|
} |