|
<!DOCTYPE html> |
|
<head> |
|
<meta charset="utf-8"> |
|
<script src="https://d3js.org/d3.v4.min.js"></script> |
|
<style> |
|
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } |
|
|
|
.axis path { |
|
display: none; |
|
} |
|
|
|
.axis.y line { |
|
stroke: silver; |
|
} |
|
|
|
</style> |
|
</head> |
|
|
|
<body> |
|
<script> |
|
var margin = {'top': 20, 'right': 40, 'bottom': 20, 'left': 20}; |
|
var width = 400 - margin.right - margin.left; |
|
var height = 300 - margin.top - margin.bottom; |
|
|
|
function translate(x, y) { |
|
return 'translate(' + x + ',' + y + ')'; |
|
} |
|
|
|
var svg = d3.select('body').append('svg') |
|
.attr('width', width + margin.right + margin.left) |
|
.attr('height', height + margin.top + margin.bottom) |
|
.append('g') |
|
.attr('transform', translate(margin.left, margin.top)); |
|
|
|
d3.csv('oecd.csv', function(data) { |
|
data = data.filter(function(d) { |
|
return d.HEALTHEXP !== "NA" && d.LIFEEXP !== "NA"; |
|
}); |
|
|
|
var dataByYear = d3.nest() |
|
.key(function(d) { return d.TIME; }) |
|
.entries(data); |
|
|
|
console.log(dataByYear); |
|
|
|
var healthExpenditures = data.map(function(d) { return +d.HEALTHEXP; }); |
|
|
|
var lifeExpectancies = data.map(function(d) { return +d.LIFEEXP}); |
|
|
|
var xScale = d3.scaleLinear() |
|
.domain([0, d3.max(healthExpenditures)]) |
|
.range([0, width]); |
|
|
|
var yScale = d3.scaleLinear() |
|
.domain(d3.extent(lifeExpectancies)) |
|
.range([height, 0]); |
|
|
|
var xAxis = d3.axisBottom(xScale).ticks(4); |
|
|
|
var yAxis = d3.axisLeft(yScale) |
|
.ticks(4) |
|
.tickSize(width); |
|
|
|
svg.append('g') |
|
.attr('class', 'axis x') |
|
.attr('transform', translate(0, height)) |
|
.call(xAxis); |
|
|
|
svg.append('g') |
|
.attr('class', 'axis y') |
|
.attr('transform', translate(width, 0)) |
|
.call(yAxis); |
|
|
|
function update(data) { |
|
var circles = svg.selectAll('circle') |
|
.data(data, function(d) { return d.LOCATION; }); |
|
|
|
circles.exit().remove(); |
|
|
|
circles.enter().append('circle') |
|
.attr('r', 3) |
|
.attr('fill', 'black') |
|
.merge(circles) |
|
.attr('cx', function(d) { |
|
return xScale(+d.HEALTHEXP); |
|
}) |
|
.attr('cy', function(d) { |
|
return yScale(+d.LIFEEXP); |
|
}); |
|
|
|
var labels = svg.selectAll('text.label') |
|
.data(data.filter(function(d) { |
|
return d.LOCATION === "USA" || d.LOCATION === "JPN"; |
|
}), function(d) { return d.LOCATION; }); |
|
|
|
labels.exit().remove(); |
|
|
|
labels.enter().append('text') |
|
.attr('class', 'label') |
|
.text(function(d) { return d.LOCATION; }) |
|
.attr('dx', 5) |
|
.attr('dy', 3) |
|
.merge(labels) |
|
.attr('transform', function(d) { |
|
return translate(xScale(+d.HEALTHEXP), yScale(+d.LIFEEXP)); |
|
}) |
|
} |
|
|
|
var i = 0; |
|
d3.interval(function() { |
|
if (i < dataByYear.length) update(dataByYear[i++].values); |
|
}, 250); |
|
}) |
|
</script> |
|
</body> |