Built with blockbuilder.org
forked from drvid's block: stacked bars
license: mit |
Built with blockbuilder.org
forked from drvid's block: stacked bars
<!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 width = 860; | |
var height = 450; | |
// Feel free to change or delete any of the code you see in this editor! | |
var svg = d3.select("body").append("svg") | |
.attr("width", width+100) | |
.attr("height", height+100) | |
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 = [] | |
var all_data = [] | |
data.months.map(function(m) { | |
if (!months.includes(m[0])) { | |
months.push(m[0]); | |
var month_data = {}; | |
month_keys.forEach((key,i) => month_data[key] = m[i]); | |
all_data.push(month_data); | |
} | |
}) | |
console.log("months", months) | |
console.log("all_data", all_data) | |
var stack = d3.stack().keys(["due", "over"]); | |
var series = stack(all_data); | |
console.log("series", series) | |
var x = d3.scaleBand() | |
.domain(months) | |
.rangeRound([0, width]) | |
.padding(0.1), | |
y = d3.scaleLinear() | |
.domain([0, d3.max(all_data.map(function(o){ return o.due }))]) | |
.rangeRound([height, 0]); | |
svg.append("g") | |
.attr("class", "axis") | |
.attr("transform", "translate(0," + height + ")") | |
.call(d3.axisBottom(x)); | |
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) { | |
console.log("x is", d.data.label); | |
return x(d.data.label); }) | |
.attr("y", function (d) { | |
console.log("y is ", d[1]) | |
return y(d[1]); }) | |
.attr("height", function (d) { | |
console.log("height is ", y(d[0])) | |
return y(d[0])}) | |
.attr("width", x.bandwidth()); | |
</script> | |
</body> |