// Note: http://alignedleft.com/tutorials/d3/making-a-bar-chart // width and height var w = 500; var h = 100; var barPadding = 1; var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13, 11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ]; var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); // Note: With D3, you always have to select whatever it is you're // about to act on, even if that selection is momentarily empty. svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", function(d, i) { return i * w / dataset.length; }) .attr("y", function(d) { return h - d * 4; }) .attr("width", w / dataset.length - barPadding) .attr("height", function(d) { return d * 4; }) .attr("fill", function(d) { return "rgb(0, 0, " + d * 10 + ")"; }); // Note: First, select what you want, bring in the data, enter the // new elements (which are just placeholders at this point), and finally // append the new text elements to the DOM. svg.selectAll("text") .data(dataset) .enter() .append("text") .text(function(d) { return d; }) .attr("x", function(d, i) { return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2; }) .attr("y", function(d) { return h - (d * 4) + 14; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") .attr("fill", "white") .attr("text-anchor", "middle")