Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active February 8, 2016 23:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mbostock/882152 to your computer and use it in GitHub Desktop.
Save mbostock/882152 to your computer and use it in GitHub Desktop.
Grouped Bar Chart
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis text {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var n = 20, // number of samples
m = 4; // number of series
var data = d3.range(m).map(function() { return d3.range(n).map(Math.random); });
var margin = {top: 20, right: 30, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var y = d3.scale.linear()
.domain([0, 1])
.range([height, 0]);
var x0 = d3.scale.ordinal()
.domain(d3.range(n))
.rangeBands([0, width], .2);
var x1 = d3.scale.ordinal()
.domain(d3.range(m))
.rangeBands([0, x0.rangeBand()]);
var z = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("svg:g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g").selectAll("g")
.data(data)
.enter().append("g")
.style("fill", function(d, i) { return z(i); })
.attr("transform", function(d, i) { return "translate(" + x1(i) + ",0)"; })
.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("height", y)
.attr("x", function(d, i) { return x0(i); })
.attr("y", function(d) { return height - y(d); });
</script>
@djjr
Copy link

djjr commented May 10, 2013

Is there a logic that eludes me on why "y" is used for horizontal and "x" for vertical in this snippet?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment