Skip to content

Instantly share code, notes, and snippets.

@d3indepth
Last active August 2, 2017 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d3indepth/30a7091e97b03eeba2a6a3ca1067ca92 to your computer and use it in GitHub Desktop.
Save d3indepth/30a7091e97b03eeba2a6a3ca1067ca92 to your computer and use it in GitHub Desktop.
Stack generator (bar)
license: gpl-3.0
height: 110
border: no
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Stack generator (bar)</title>
</head>
<style>
</style>
<body>
<svg width="700" height="100">
<g></g>
</svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script>
<script>
var colors = ['#FBB65B', '#513551', '#de3163'];
var data = [
{day: 'Mon', apricots: 120, blueberries: 180, cherries: 100},
{day: 'Tue', apricots: 60, blueberries: 185, cherries: 105},
{day: 'Wed', apricots: 100, blueberries: 215, cherries: 110},
{day: 'Thu', apricots: 80, blueberries: 230, cherries: 105},
{day: 'Fri', apricots: 120, blueberries: 240, cherries: 105}
];
var stack = d3.stack()
.keys(['apricots', 'blueberries', 'cherries']);
var stackedSeries = stack(data);
// Create a g element for each series
var g = d3.select('g')
.selectAll('g.series')
.data(stackedSeries)
.enter()
.append('g')
.classed('series', true)
.style('fill', function(d, i) {
return colors[i];
});
// For each series create a rect element for each day
g.selectAll('rect')
.data(function(d) {
return d;
})
.enter()
.append('rect')
.attr('width', function(d) {
return d[1] - d[0];
})
.attr('x', function(d) {
return d[0];
})
.attr('y', function(d, i) {
return i * 20;
})
.attr('height', 19);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment