Built with blockbuilder.org
forked from romsson's block: Grouped bar chart v4
license: mit |
Built with blockbuilder.org
forked from romsson's block: Grouped bar chart v4
<!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.v4.min.js"></script> | |
<script> | |
// Source: https://bl.ocks.org/mbostock/3887051 | |
var n = 10, // number of samples | |
m = 5; // number of series | |
var raw = d3.range(m * n).map(function(d, i) { | |
return {"cat": (i % m), "value": Math.random()}}); | |
var data = d3.nest() | |
.key(function(d, i) { return d.cat; }) | |
.entries(raw) | |
console.log(data) | |
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.scaleLinear() | |
.domain([0, 1]) | |
.range([height, 0]); | |
var x0 = d3.scaleBand() | |
.domain(d3.range(n)) | |
.range([0, width], .2); | |
var x1 = d3.scaleBand() | |
.domain(d3.range(m)) | |
.range([0, x0.bandwidth() - 10]); | |
var z = d3.scaleOrdinal() | |
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); | |
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 + ")"); | |
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.values; }) | |
.enter().append("rect") | |
.attr("width", x1.bandwidth()) | |
.attr("height", function(d) { return y(d.value); }) | |
.attr("x", function(d, i) { return x0(i); }) | |
.attr("y", function(d) { return height - y(d.value); }); | |
</script> |