D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
EmbraceLife
Full window
Github gist
2. vertical barChart
Key
padding is done by barWidth - 1
<!DOCTYPE html> <meta charset="utf-8"> <style> .chart rect { fill: orange; } .chart text { fill: steelblue; font: 10px sans-serif; text-anchor: middle; } </style> <svg class="chart"></svg> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var width = 960, height = 500; var chart = d3.select(".chart") .attr("width", width) .attr("height", height); var yScale = d3.scaleLinear() // set px-range: from bottom to top => [height, 0] .range([height, 0]); function type(d) { // coerce into numeric values from string // round decimal using Math.round*100/100 d.value = Math.round(+d.value*100)/100; return d; } d3.tsv("data.tsv", type, function(error, data) { yScale.domain([0, d3.max(data, function(d) { return d.value; })]); // set barWidth using SVG's width / data.length var barWidth = width / data.length; var bar = chart.selectAll("g") .data(data) .enter() .append("g") .attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; }); bar.append("rect") // rect's y coord default is 0 inherited from g // set each rect's topLeft corner's "y" coord .attr("y", function(d) { return yScale(d.value); }) // set each rect's height using canvas height and y coord .attr("height", function(d) { return height - yScale(d.value); }) .attr("width", barWidth - 1); // step 7 bar.append("text") // set each text's x coord .attr("x", barWidth / 2) // set each text's y coord .attr("y", function(d) { return yScale(d.value) + 3; }) .attr("dy", ".75em") .text(function(d) { return d.value; }); // attr text-anchor is set to middle }); </script>
https://d3js.org/d3.v4.min.js