Skip to content

Instantly share code, notes, and snippets.

@chloerulesok
Last active October 29, 2017 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chloerulesok/926dcca08911c3384da7cea9dae01c41 to your computer and use it in GitHub Desktop.
Save chloerulesok/926dcca08911c3384da7cea9dae01c41 to your computer and use it in GitHub Desktop.
Dynamic bar widths
license: mit
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment