xxxxxxxxxx
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cleaning Up</title>
<script type="text/javascript" src="https://d3js.org/d3.v3.js"></script>
<style type="text/css">
body {
background-color: white;
font-family: Helvetica, Arial, sans-serif;
}
h1 {
font-size: 40px;
margin: 0;
}
p {
font-size: 13px;
margin: 20px 20 0 0;
}
svg {
background-color: white;
}
rect:hover {
fill: steelblue;
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 13px;
}
.y.axis path,
.y.axis line {
opacity: 0;
}
</style>
</head>
<body>
<h1> Top 20 countries by woodland </h1>
<p> Forest area per country (km<SUP>2</SUP>, 2012)</p>
<script type="text/javascript">
// set width and height of viz, plus padding
var w = 700;
var h = 600;
var padding = [ 10, 25, 20, 120 ]; //Top, right, bottom, left
// make width scale, set as linear (to hold numbers). Subtract padding
var widthScale = d3.scale.linear()
.range([ 0, w - padding[1] - padding[3] ]);
// make height scale, set as ordinal (eg categories). Subtract padding.
var heightScale = d3.scale.ordinal()
.rangeRoundBands([ padding[0], h - padding[2] ], 0.2);
// create horizontal axis and place it on the bottom
var xAxis = d3.svg.axis()
.scale(widthScale)
.orient("bottom");
// create veritcal axis and place it on the left
var yAxis = d3.svg.axis()
.scale(heightScale)
.orient("left");
// create a holder for the SVG in the body, give it the width and height set earlier
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
// call the data
d3.csv("forestdata.csv", function(data) {
// sort the data, descending
data.sort(function(a, b) {
return d3.descending(+a.forest2012Km2, +b.forest2012Km2);
});
// make axis width scalable to biggest value
widthScale.domain([ 0, d3.max(data, function(d) {
return +d.forest2012Km2;
}) ]);
// make axis height scalable to biggest value
heightScale.domain(data.map(function(d) { return d.country; } ));
// create a rectangle for each line of data
var rects = svg.selectAll("rect")
.data(data)
.enter()
.append("rect");
// add padding between bars. set fill color. assemble tooltip
rects.attr("x", padding[3])
.attr("y", function(d) {
return heightScale(d.country);
})
.attr("width", function(d) {
return widthScale(d.forest2012Km2);
})
.attr("height", heightScale.rangeBand())
.attr("fill", "green")
.append("title")
.text(function(d) {
return d.country + "'s forest area is " + d.forest2012Km2 + " km2" ;
});
// draw horizontal axis, allow for padding
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(" + padding[3] + "," + (h - padding[2]) + ")")
.call(xAxis);
// draw vertical axis, allow for padding
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + padding[3] + ",0)")
.call(yAxis);
});
</script>
<p>Source : Banque mondiale<p>
</body>
</html>
Modified http://d3js.org/d3.v3.js to a secure url
https://d3js.org/d3.v3.js