D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
dyorama
Full window
Github gist
Module 3, Exercice 3, version 2
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Forest area in 2012 in km2</title> <script type="text/javascript" src="https://d3js.org/d3.v3.js"></script> <style type="text/css"> body { background-color: white; } svg { background-color: white; } rect { fill: green; } </style> </head> <body> <h1> Top 20 countries by woodland </h1> <p>Forest area per country (km2, 2012)</p> <!-- BEGIN CHART --> <script type="text/javascript"> // make svg element to hold the chart var svg = d3.select("body") .append("svg") .attr("width", 1200) .attr("height", 600); // load CSV data d3.csv("forestdata.csv", function(data) { // sort bars in descending order data.sort(function(a, b) { return d3.descending(+a.forest2012Km2, +b.forest2012Km2); //If your numeric values aren't sorting properly, //try commenting out the line above, and instead using: // //return d3.descending(+a.lifeSatisfaction, +b.lifeSatisfaction); // //Data coming in from the CSV is saved as strings (text), //so the + signs here force JavaScript to treat those //strings instead as numeric values, thereby fixing the //sort order (hopefully!). }); // create rectangles for each data value var rects = svg.selectAll("rect") .data(data) .enter() .append("rect"); // set size for the bars. start each bar at Opx acriss to leave room for labels, and move down 12px for the next bar. rects.attr("x", 110) .attr("y", function(d, i) { return i * 30; }) // divide the data value by 10,000 to fit the scale .attr("width", function(d) { return d.forest2012Km2 / 10000; }) // allot 10px for each bar and compose tooltip .attr("height", 30) .append("title") .text(function(d) { return d.country + "'s forest area is " + d.forest2012Km2 + " km2" ; }) // add axis labels on left, 15px apart, starting at 9px down and 140px across svg.selectAll("text") .data(data) .enter() .append("text") .text(function(d){ return d.country; }) .attr("x", 0) .attr("y", function(d, i){ return i * 30 + 18; }) // type attributes for the labels .attr({ "fill": "black", "font-family": "sans-serif", "font-size": "13px", "text-anchor": "start" }) }); </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