D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
ajzeigert
Full window
Github gist
Chart comparing CPI change from 1974-2014
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>CPI change</title> <script type="text/javascript" src="https://d3js.org/d3.v3.js"></script> </head> <style> body { font-family: 'Helvetica', Arial, sans-serif; margin: 0; padding: 0; } #container { width: 620px; margin: 20px; } h1 { font-size: 26px; margin: 0; } p { margin: 0; } small { font-size: 10px; } .source, .credit { display: inline-block; } .source { float: left; } .credit { float: right; } /* SVG styles below */ rect.bar { fill: #7a9e00 } rect.bar:hover { fill: #013f62 } </style> <body> <div id='container'> <h1>Consumer Price Index for all food, 1974-2014</h1> <p>Shown as percentage change in overall price from previous year.</p> <div id='chart'></div> <p class='source'><small>Source: USDA</small></p> <p class='credit'><small>Chart by Andy Zeigert</small></p> </div> <script type="text/javascript"> d3.csv("cpi.csv", function(data) { console.log(data); var w = 600; var h = 300 var barPadding = 2; var margin = { top: 10, right: 10, bottom: 10, left: 10 }; var chart = d3.select("#chart").append("svg").attr({ width: w + margin.left + margin.right, height: h + margin.bottom + margin.top }); chart.selectAll("rect") .data(data) .enter() .append("rect") .attr({ x: function(d, i) { return i * (w / data.length) + margin.left }, y: function(d) { return h - +d["All food"] * 20 + margin.top }, width: w / data.length - barPadding, height: function(d) { return +d["All food"] * 20 }, class: "bar"}) .append("title") .text(function(d) { return d.Year + ": " + d["All food"] }); chart.selectAll("text") .data(data) .enter() .append("text") .attr({ x: function(d, i) { return i * (w / data.length) + ( w / data.length - barPadding) / 2 + margin.left }, y: function(d) { return h - (d["All food"] * 20) - 2 + margin.top }, "font-family": "sans-serif", "font-size": "9px", "font-weight": "bold", "fill": "#595959", "text-anchor": "middle" }) .text(function(d) { return d["All food"] }); chart.selectAll("text2") .data(data) .enter() .append("text") .attr({ x: function(d, i) { return i * (w / data.length) + ( w / data.length - barPadding) / 2 + margin.left }, y: function(d) { return h + margin.top + 10}, "font-family": "sans-serif", "font-size": "8px", "fill": "#595959", "text-anchor": "middle" }) .text(function(d) { return "'" + d.Year.slice(-2) }); }); </script> </body> </html>
Modified
http://d3js.org/d3.v3.js
to a secure url
https://d3js.org/d3.v3.js