D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
chloerulesok
Full window
Github gist
Dynamic bar widths
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> // *** Add or remove integer data items from this array to see dynamic bar width var data = [1,2,4,5,3,4,7,4,2,2,5]; var svgwidth = 960; // *** Calculate bar width to fill svg widthways var barwidth = (svgwidth/data.length) * 0.5; var barpadding = (svgwidth/data.length) * 0.5; var svg = d3.select("body").append("svg") .attr("width", svgwidth) .attr("height", 500) var rects = svg.selectAll("rect").data(data); rects.enter().append("rect") .attr("y", calcy) .attr("x", calcx) .attr("width", barwidth) .attr("height", calcheight) .attr("fill", "black"); function calcx(d, i){ return i * (barwidth + barpadding) + (barpadding/2); } function calcy(d){ return 200 - calcheight(d); } function calcheight(d){ return d * 20; } </script> </body>
https://d3js.org/d3.v4.min.js