Built with blockbuilder.org
Last active
October 29, 2017 11:07
-
-
Save chloerulesok/926dcca08911c3384da7cea9dae01c41 to your computer and use it in GitHub Desktop.
Dynamic bar widths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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