Skip to content

Instantly share code, notes, and snippets.

@trtg
Created October 19, 2012 07:13
Show Gist options
  • Save trtg/3916673 to your computer and use it in GitHub Desktop.
Save trtg/3916673 to your computer and use it in GitHub Desktop.
using stack layout in d3
{"endpoint":"","display":"svg","public":true,"require":[],"tab":"edit","display_percent":0.7,"play":false,"loop":false,"restart":false,"autoinit":true,"pause":true,"loop_type":"period","bv":false,"nclones":15,"clone_opacity":0.4,"duration":3000,"ease":"linear","dt":0.01}
var svg = d3.select("svg");
var color = d3.scale.category20();
//stack layout expects input array of arrays to contain
//objects which have a .y attribute
var data = [
[{y:10},{y:10},{y:10},{y:10},{y:10}],
[{y:14},{y:25},{y:21},{y:10},{y:10}],
[{y:14},{y:35},{y:21},{y:10},{y:10}],
];
var stack= d3.layout.stack();
stack(data);//modifies data in place
//find overall max of data matrix
var max = d3.max(data,function(d) {
return d3.max(d,function(v){
return v.y+v.y0;
})
})
var ch = 407;//sets height of chart
var yscale = d3.scale.linear()
.domain([0,max])
.range([0,ch]);
//if you inspect data, each object will
//have a y0 member which corresponds to the
//sum of the values above it in the same column
//of the data matrix
//console.log(data)
var group=svg.append("g")
.attr("transform","translate("+[100,100]+")")
var layers = group.selectAll("g")
.data(data)
.enter()
.append("g")
.style({
fill: function(d,i) {return color(i)}
})
console.log(yscale(-21))
var stacks=layers.selectAll("rect")
.data(function(d){return d})
.enter()
.append("rect")
.attr({
width:30,
height:function(d,i){
return yscale(d.y)
},
x:function(d,i){
return i*40
},
y:function(d,i){
return ch-yscale(d.y0+d.y)//flip rightside up
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment