D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
bartlf
Full window
Github gist
D3-course-oct-2015 Renewable Energy
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Bar Chart, Framed</title> <script type="text/javascript" src="//d3js.org/d3.v3.min.js" charset="utf-8"></script> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="container"> <h1>Use of renewable energy</h1> <p>Use of renewable energy in % of total energy generation. <strong>Source:</strong> <a href="https://data.oecd.org/energy/renewable-energy.htm#indicator-chart" target="_blank">OECD</a>, 2015</h3></a></p> </div> <script type="text/javascript"> var w = 700; var h = 900; var padding = [ 20, 10, 30, 100 ]; //Top, right, bottom, left var widthScale = d3.scale.linear() .range([ 0, w - padding[1] - padding[3] ]); var heightScale = d3.scale.ordinal() .rangeRoundBands([ padding[0], h - padding[2] ], 0.1); var xAxis = d3.svg.axis() .scale(widthScale) .orient("bottom"); var yAxis = d3.svg.axis() .scale(heightScale) .orient("left"); //Now SVG goes into #container instead of body var svg = d3.select("#container") .append("svg") .attr("width", w) .attr("height", h); d3.csv("renewable-energy.csv", function(data) { data.sort(function(a, b) { return d3.descending(+a.y2012, +b.y2012); }); widthScale.domain([ 0, d3.max(data, function(d) { return +d.y2012; }) ]); heightScale.domain(data.map(function(d) { return d.country; } )); //Bind data to groups (not bars directly) var groups = svg.selectAll("g") .data(data) .enter() .append("g") .attr("class", "bar"); //Add a rect to each group var rects = groups.append("rect") .attr("x", padding[3]) .attr("y", function(d) { return heightScale(d.country); }) .attr("width", 0) .attr("height", heightScale.rangeBand()) .attr("fill", "#fff"); //Add a text element to each group groups.append("text") .attr("x", function(d) { return padding[3] + widthScale(d.y2012) - 3; }) .attr("y", function(d) { return heightScale(d.country) + 11; }) .text(function(d) { return d.y2012; }); rects.transition() .delay(function(d, i) { return i * 50; }) .duration(1000) .attr("width", function(d) { return widthScale(d.y2012); }); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(" + padding[3] + "," + (h - padding[2]) + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(" + padding[3] + ",0)") .call(yAxis); }); </script> </body> </html>
https://d3js.org/d3.v3.min.js