Skip to content

Instantly share code, notes, and snippets.

@romsson
Created January 24, 2020 15:51
Show Gist options
  • Save romsson/4bcda26d1704c30269cfcc24c3339264 to your computer and use it in GitHub Desktop.
Save romsson/4bcda26d1704c30269cfcc24c3339264 to your computer and use it in GitHub Desktop.
grouped bar chart
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var margin = {top: 20, right: 10, bottom: 20, left: 10};
var width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var n = 10, // number of samples
m = 5; // number of series
var max = 0;
var data = d3.range(m).map(function() {
var d = d3.range(n).map(Math.random);
max = Math.max(max, d3.max(d));
return d;
});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + ", " + margin.top + ")")
var x = d3.scaleBand()
.domain(d3.range(m))
.range([0, width])
.paddingInner(.5)
var x2 = d3.scaleBand()
.domain(d3.range(n))
.range([0, x.bandwidth()])
var y = d3.scaleLinear()
.domain([0, max])
.range([0, height])
svg.selectAll("g").data(data)
.enter()
.append("g")
//.style("stroke", "black")
//.style("fill", "white")
//.attr("x", function(d, i) { return x(i);})
//.attr("y", function(d, i) { return height - y(d3.max(d));})
//.attr("width", function(d, i) { return x.bandwidth(); })
//.attr("height", function(d, i) { return y(d3.max(d)) })
.attr("transform", function(d, i) { return "translate(" + x(i) + ", 0)" })
.selectAll("rect")
.data(function(d) { return d; })
.enter()
.append("rect")
.style("stroke", "black")
.style("fill", "white")
.attr("x", function(d, i) { return x2(i);})
.attr("y", function(d, i) { return height - y(d);})
.attr("width", function(d, i) { return x2.bandwidth(); })
.attr("height", function(d, i) { return y(d) })
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment