Skip to content

Instantly share code, notes, and snippets.

@drvid
Created March 26, 2019 19:56
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 drvid/7fd8a65c86a10b9e5d148218d627e6ba to your computer and use it in GitHub Desktop.
Save drvid/7fd8a65c86a10b9e5d148218d627e6ba to your computer and use it in GitHub Desktop.
stacked bars
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var data = {
"period": "yearly",
"range": "January 1, 2019 - December 31, 2019",
"months": [
["January 2019", 309, 124, "2019-01-01", "2019-01-31"],
["February 2019", 278, 126, "2019-02-01", "2019-02-28"],
["March 2019", 230, 50, "2019-03-01", "2019-03-31"],
["April 2019", 2, 0, "2019-04-01", "2019-04-30"],
["May 2019", 0, 0, "2019-05-01", "2019-05-31"],
["June 2019", 0, 0, "2019-06-01", "2019-06-30"],
["July 2019", 0, 0, "2019-07-01", "2019-07-31"],
["August 2019", 0, 0, "2019-08-01", "2019-08-31"],
["September 2019", 0, 0, "2019-09-01", "2019-09-30"],
["October 2019", 0, 0, "2019-10-01", "2019-10-31"],
["November 2019", 0, 0, "2019-11-01", "2019-11-30"],
["December 2019", 0, 0, "2019-12-01", "2019-12-31"]
],
"jobs": {
"due": 860,
"over": 315,
"start": "2019-01-01",
"end": "2019-12-31"
}
};
var month_keys = ["label", "due", "over", "start", "end"];
var months = []
data.months.map(function(m) {
var month = {}
month_keys.forEach((key, i) => month[key] = m[i]);
months.push(month);
})
var stack = d3.stack().keys(["due", "over"]);
var series = stack(months);
var x = d3.scaleBand()
.domain(data.range)
.rangeRound([0, width])
.padding(0.1),
y = d3.scaleLinear()
.domain([0, d3.max(months.map(function(o){ return o.due }))])
.rangeRound([height, 0]);
var layer = svg.selectAll(".stack")
.data(series).enter()
.append("g")
.attr("class", "stack")
.style("fill": "blue");
layer.selectAll("rect").data(function (d) { return d; })
.enter().append("rect")
.attr("x", function (d) { return x(d.x); })
.attr("y", function (d) { return y(d.y + d.y0); })
.attr("height", function (d) { return y(d.y0) - y(d.y + d.y0); })
.attr("width", x.rangeBand());
// Feel free to change or delete any of the code you see in this editor!
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment