Skip to content

Instantly share code, notes, and snippets.

@heavysixer
Forked from ZJONSSON/index.html
Created October 9, 2012 17:01
Show Gist options
  • Save heavysixer/3860054 to your computer and use it in GitHub Desktop.
Save heavysixer/3860054 to your computer and use it in GitHub Desktop.
barStack - stacking with negative values
<!DOCTYPE html>
<html>
<head>
<script src="http://mbostock.github.com/d3/d3.v2.js"></script>
<title>barStack</title>
<style>
.axis text {
font: 10px sans-serif;
}
.axis path, .axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
</head>
<body>
<script type="text/javascript" >
function barStack(d) {
var l = d[0].length
while (l--) {
var posBase = 0, negBase = 0;
d.forEach(function(d) {
d=d[l]
d.size = Math.abs(d.y)
if (d.y<0) {
d.y0 = negBase
negBase-=d.size
} else
{
d.y0 = posBase = posBase + d.size
}
})
}
d.extent= d3.extent(d3.merge(d3.merge(d.map(function(e) { return e.map(function(f) { return [f.y0,f.y0-f.size]})}))))
return d
}
/* Here is an example */
var data = [[{y:300},{y:600},{y:-300}],
[{y:400},{y:-200},{y:-900}],
[{y:100},{y:-100},{y:-100}],
[{y:1000},{y:-300},{y:400}]]
var h=500
,w=500
,margin=10
,color = d3.scale.category10()
,x = d3.scale.ordinal()
.domain(d3.range(data[0].length+1))
.rangeRoundBands([margin,w-margin], .1)
,y = d3.scale.linear()
.range([h-margin,0+margin])
,xAxis = d3.svg.axis().scale(x).orient("bottom").tickSize(6, 0)
,yAxis = d3.svg.axis().scale(y).orient("left")
barStack(data)
console.log(data)
y.domain(data.extent)
svg = d3.select("body")
.append("svg")
.attr("height",h)
.attr("width",w)
svg.selectAll(".series").data(data)
.enter().append("g").classed("series",true).style("fill", function(d,i) { return color(i)})
.selectAll("rect").data(Object)
.enter().append("rect")
.attr("x",function(d,i) { return x(i)})
.attr("y",function(d) { return y(d.y0)})
.attr("height",function(d) { console.log(d);
console.log(y(0)-y(d.size));
return y(0)-y(d.size)})
.attr("width",x.rangeBand())
svg.append("g").attr("class","axis x").attr("transform","translate (0 "+y(0)+")").call(xAxis)
svg.append("g").attr("class","axis y").attr("transform","translate ("+x(margin)+" 0)").call(yAxis)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment