Last active
July 18, 2016 18:19
-
-
Save santi698/e2ab8942f2e7f1e7251708e54133c0c2 to your computer and use it in GitHub Desktop.
Stacked Bar Chart
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> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>D3: Stack layout stacked bar chart</title> | |
<script type="text/javascript" src="//d3js.org/d3.v3.min.js"></script> | |
<style type="text/css"> | |
/* No style rules here yet */ | |
</style> | |
</head> | |
<body> | |
<script> | |
//Width and height | |
var w = 500; | |
var h = 300; | |
//Original data | |
var dataset = [ | |
[ | |
{ x: 0, y: 5 }, | |
{ x: 1, y: 4 }, | |
{ x: 2, y: 2 }, | |
{ x: 3, y: 7 }, | |
{ x: 4, y: 23 } | |
], | |
[ | |
{ x: 0, y: 10 }, | |
{ x: 1, y: 12 }, | |
{ x: 2, y: 19 }, | |
{ x: 3, y: 23 }, | |
{ x: 4, y: 17 } | |
], | |
[ | |
{ x: 0, y: 22 }, | |
{ x: 1, y: 28 }, | |
{ x: 2, y: 32 }, | |
{ x: 3, y: 35 }, | |
{ x: 4, y: 43 } | |
] | |
]; | |
//Set up stack method | |
var stack = d3.layout.stack(); | |
//Data, stacked | |
stack(dataset); | |
//Set up scales | |
var xScale = d3.scale.ordinal() | |
.domain(d3.range(dataset[0].length)) | |
.rangeRoundBands([0, w], 0.05); | |
var yScale = d3.scale.linear() | |
.domain([0, | |
d3.max(dataset, function(d) { | |
return d3.max(d, function(d) { | |
return d.y0 + d.y; | |
}); | |
}) | |
]) | |
.range([0, h]); | |
//Easy colors accessible via a 10-step ordinal scale | |
var colors = d3.scale.category10(); | |
//Create SVG element | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", w) | |
.attr("height", h); | |
// Add a group for each row of data | |
var groups = svg.selectAll("g") | |
.data(dataset) | |
.enter() | |
.append("g") | |
.style("fill", function(d, i) { | |
return colors(i); | |
}); | |
// Add a rect for each data value | |
var rects = groups.selectAll("rect") | |
.data(function(d) { return d; }) | |
.enter() | |
.append("rect") | |
.attr("x", function(d, i) { | |
return xScale(i); | |
}) | |
.attr("y", function(d) { | |
return h - yScale(d.y0 + d.y); | |
}) | |
.attr("height", function(d) { | |
return yScale(d.y); | |
}) | |
.attr("width", xScale.rangeBand()); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment