Skip to content

Instantly share code, notes, and snippets.

@lewis500
Created August 18, 2013 23:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lewis500/6264512 to your computer and use it in GitHub Desktop.
Save lewis500/6264512 to your computer and use it in GitHub Desktop.
Stacked Bar Chart Example
{"description":"Stacked Bar Chart Example","endpoint":"","display":"svg","public":true,"require":[],"fileconfigs":{"_.md":{"default":true,"vim":false,"emacs":false,"fontSize":12},"config.json":{"default":true,"vim":false,"emacs":false,"fontSize":12},"inlet.js":{"default":true,"vim":false,"emacs":false,"fontSize":12},"inlet.svg":{"default":true,"vim":false,"emacs":false,"fontSize":12}},"fullscreen":false,"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,"editor_editor":{"coffee":false,"vim":false,"emacs":false,"width":579,"height":573,"hide":false},"thumbnail":"http://i.imgur.com/zleU5Kw.png"}
var svg = d3.select("svg");
var color = d3.scale.category20(); //a color scale that d3 has built in!
var data = [
[{y:21},{y:10},{y:10},{y:38},{y:20}],
[{y:14},{y:25},{y:21},{y:10},{y:10}],
[{y:14},{y:35},{y:21},{y:10},{y:4}]
];
var stack = d3.layout.stack();
stack(data); //stackifying the data
var max = d3.max(data, function(d) {
return d3.max(d, function(v) {
return v.y + v.y0
})
})
var height = 416;
var yscale = d3.scale.linear()
.domain([0, max])
.range([0, height]);
var group = svg.append("g") //create a group so you can move everything around together
.attr("transform", "translate(" + [100, 100] + ")")
var layers = group.selectAll("g")
.data(data)
.enter()
.append("g")
.style({
fill: function(d,i) { return color(i) }
})
var stacks = layers.selectAll("rect")
.data(function(d) { return d }) //create one shape for each data point
.enter()
.append("rect")
.attr({
width: 30,
height: function(d,i) {
return yscale(d.y)
},
x: function(d,i) {
return i * 40 //this is just a way to make the bars a certain distance apart
},
y: function(d,i) {
return height - yscale(d.y0 + d.y) //subtract cause you flip it!
}
})
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment