D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
kcsluis
Full window
Github gist
Bar Graph
<!DOCTYPE html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> body { font-family: sans-serif; } .barPositive { fill: #333; } .barNegative { fill: #ccc; } .axis text { font-size: 10px; fill: #777; } .axis path { display: none; } .axis line { stroke-width:1px; stroke: #ccc; stroke-dasharray: 2px 2px; } </style> </head> <body> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script> <script> var margin = {top: 20, right: 20, bottom: 20, left: 60}; var width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // ordinal scale and rangeRoundBands are uniquely important for bar graphs var x = d3.scale.ordinal() .rangeRoundBands([0, width], 0.33); var y = d3.scale.linear() .range([height, 0]); var xAxis = d3.svg.axis() .scale(x) .tickSize(-height) .tickPadding(8) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .tickSize(-width) .tickPadding(8) .orient("left"); d3.tsv("jobs.tsv", ready); function ready(err, data) { if (err) throw "error loading data"; data.forEach(function(d) { d.jobs_change = +d.jobs_change; d.private_job_change = +d.private_job_change; d.unemployment_rate = +d.unemployment_rate; var s = d.month_year.split("-"); d.date = new Date(s[0], (+s[1]-1) ); }); y.domain(d3.extent(data, function (d) { return d.jobs_change; })); data.sort(function(a,b) { return a.date - b.date; }); x.domain(data.map( function (d) { return d.month_year; })); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + (height) + ")") .call(xAxis) // selectAll text to update axis text .selectAll("text") .text(function (d) { var dateSplit = d.split("-"); if ( dateSplit[1] === "01" ) { return dateSplit[0]; }; }); svg.append("g") .attr("class", "y axis") .call(yAxis) .selectAll("text") .text( function (d) { var changeLabel = d; return d = (changeLabel > 0) ? "+" + d + "k" : d + "k"; }); var rect = svg.append("g").attr("class", "g-rect-group").selectAll("rect") .data(data) .enter() .append("rect") // ternary to add positive or negative class to bars .attr("class", function (d) { return (d.jobs_change > 0) ? 'bar barPositive' : 'bar barNegative'; }) // .rangeBand() function with rangeRoundBand to properly space bars .attr("width", x.rangeBand()) .attr("x", function(d) { return x(d.month_year); }) // fancy absolute values to handle positive and negative values .attr("y", function(d) { return y(Math.max(d.jobs_change, 0)); }) .attr("height", function(d) { return Math.abs(y(d.jobs_change) - y(0)); }); }; </script>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js