xxxxxxxxxx
<html>
<head>
<meta charset="utf-8">
<title>Data Visualization and Infographics with D3! (Module 4)</title>
<meta name="author" content="Matt Smith" />
<script type="text/javascript" src="https://d3js.org/d3.v3.js"></script>
<style>
body { background-color:#FFF; font-family: Helvetica, Arial, sans-serif; }
h1 { font-size:20px; font-weight:bold }
svg { background-color:#FFF; border-color: #CCC; border-style: solid; border-width: 1px; box-shadow: 4px 4px 1px #EEE; }
.bar { fill: #007FFF; }
.bar:hover { fill: #B20000; }
p { font-size:14px; }
.xaxis path, .xaxis line { fill: none; stroke: #CCC; }
.yaxis path, yaxis line { opacity: 0; }
text { fill: #000; font-family: Helvetica, Arial, sans-serif; }
.yaxis text { font-size:11px; }
.xaxis text { font-size:12px; }
</style>
</head>
<body>
<h1>Population growth projections for Canberra (2010 - 2059)</h1>
<p>This horizontal bar graph shows a projection of the total population (in thousands) of Canberra. Source: <a href="https://www.data.act.gov.au/People-and-Society/Population-Growth/8eq7-rz25">data.act.gov.au</a>, 2014.</p>
<script type="text/javascript">
// Set width and height
var w = 600;
var h = 700;
var padding = [ 0, 10, 50, 60 ];
// Set scales
var widthScale = d3.scale.linear()
.range([ 0, w - padding[1] - padding[3] ]);
var heightScale = d3.scale.ordinal()
.rangeRoundBands([ padding[0], h - padding[2] ], 0.15);
// Create svg canvas
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
// Create axis
var xAxis = d3.svg.axis()
.scale(widthScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(heightScale)
.orient("left");
// Load external data file
d3.csv("Population_Growth_Canberra.csv", function(popdata){
// Sort data by Year
popdata.sort(function(a, b){
return d3.ascending(+a.Year, +b.Year);
});
// Auto domain scaling
widthScale.domain([ 0, d3.max(popdata, function(d) {
return +d.Total / 1000;
}) ]);
heightScale.domain(popdata.map(function(d) { return d.Year; } ));
// Set rects variable
var rects = svg.selectAll("rects")
.data(popdata)
.enter()
.append("rect");
// Bind data to rectangles
rects.attr("x", padding[3])
.attr("y", function(d, i) {
return heightScale(d.Year);
})
.attr("width", function(d) {
return widthScale(d.Total / 1000);
})
.attr("height", heightScale.rangeBand())
.attr("class", "bar")
.append("title")
.text(function(d) {
return "In the year " + d.Year + ", Canberra's total projected population will be " + d.Total + "."
});
// Load axis
svg.append("g")
.attr("transform", "translate(" + padding[3] + "," + (h - padding[2])
+ ")")
.attr("class", "xaxis")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(" + padding[3] + ",0)")
.attr("class", "yaxis")
.call(yAxis);
});
</script>
</body>
</html>
Modified http://d3js.org/d3.v3.js to a secure url
https://d3js.org/d3.v3.js