A diverging stacked bar chart, with negative values descending below the x-axis.
-
-
Save rockResolve/70a975117b6f974c4716a6cf126b75b2 to your computer and use it in GitHub Desktop.
Stacked Negative Values
This file contains hidden or 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: gpl-3.0 |
This file contains hidden or 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> | |
<meta charset="utf-8"> | |
<svg width="960" height="500"></svg> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
var data = [ | |
{year: "2013-2014", new: 22, open: 160, acceptable: -11, cancelled: -1, superceeded: -0}, | |
{year: "2014-2015", new: 21, open: 170, acceptable: -11, cancelled: -2, superceeded: -1}, | |
{year: "2015-2016", new: 25, open: 178, acceptable: -12, cancelled: -1, superceeded: -0}, | |
{year: "2016-2017", new: 28, open: 190, acceptable: -15, cancelled: -1, superceeded: -1}, | |
{year: "2017-", new: 8, open: 202, acceptable: -4, cancelled: -1, superceeded: -1} | |
]; | |
var series = d3.stack() | |
.keys(["open", "new", "acceptable", "cancelled", "superceeded"]) | |
.offset(d3.stackOffsetDiverging) | |
(data); | |
var svg = d3.select("svg"), | |
margin = {top: 20, right: 30, bottom: 30, left: 60}, | |
width = +svg.attr("width"), | |
height = +svg.attr("height"); | |
var x = d3.scaleBand() | |
.domain(data.map(function(d) { return d.year; })) | |
.rangeRound([margin.left, width - margin.right]) | |
.padding(0.1); | |
var y = d3.scaleLinear() | |
.domain([d3.min(series, stackMin), d3.max(series, stackMax)]) | |
.rangeRound([height - margin.bottom, margin.top]); | |
var z = d3.scaleOrdinal(d3.schemeCategory10); | |
svg.append("g") | |
.selectAll("g") | |
.data(series) | |
.enter().append("g") | |
.attr("fill", function(d) { return z(d.key); }) | |
.selectAll("rect") | |
.data(function(d) { return d; }) | |
.enter().append("rect") | |
.attr("width", x.bandwidth) | |
.attr("x", function(d) { return x(d.data.year); }) | |
.attr("y", function(d) { return y(d[1]); }) | |
.attr("height", function(d) { return y(d[0]) - y(d[1]); }) | |
svg.append("g") | |
.attr("transform", "translate(0," + y(0) + ")") | |
.call(d3.axisBottom(x)); | |
svg.append("g") | |
.attr("transform", "translate(" + margin.left + ",0)") | |
.call(d3.axisLeft(y)); | |
function stackMin(serie) { | |
return d3.min(serie, function(d) { return d[0]; }); | |
} | |
function stackMax(serie) { | |
return d3.max(serie, function(d) { return d[1]; }); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment