This example is a rewrite of the Stacked Negative Values example from Mike Bostock using d3-template.
Last active
September 30, 2018 18:24
-
-
Save ErikOnBike/9b06335a4b87bb7a5208413ad3fc84c6 to your computer and use it in GitHub Desktop.
Rewrite of Mike Rostock's Stacked Negative Values gist using d3-template
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: gpl-3.0 |
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> | |
<meta charset="utf-8"> | |
<svg width="960" height="500"> | |
<g data-repeat="{{d}}"> | |
<g data-attr-fill="{{z(d.key)}}" data-repeat="{{d}}"> | |
<rect data-attr-x="{{x(d.data.month)}}" | |
data-attr-y="{{y(d[1])}}" | |
data-attr-width="{{x.bandwidth(d)}}" | |
data-attr-height="{{y(d[0]) - y(d[1])}}"> | |
</rect> | |
</g> | |
</g> | |
</svg> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script src="https://unpkg.com/d3-template-plugin/build/d3-template.min.js"></script> | |
<script> | |
var data = [ | |
{month: "Q1-2016", apples: 3840, bananas: 1920, cherries: -1960, dates: -400}, | |
{month: "Q2-2016", apples: 1600, bananas: 1440, cherries: -960, dates: -400}, | |
{month: "Q3-2016", apples: 640, bananas: 960, cherries: -640, dates: -600}, | |
{month: "Q4-2016", apples: 320, bananas: 480, cherries: -640, dates: -400} | |
]; | |
var series = d3.stack() | |
.keys(["apples", "bananas", "cherries", "dates"]) | |
.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.month; })) | |
.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); | |
// Render data onto template | |
svg.template().render(series); | |
// Append axis | |
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