D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
aaizemberg
Full window
Github gist
Marimekko
source: https://bl.ocks.org/mbostock/1005090
<!DOCTYPE html> <meta charset="utf-8"> <title>Marimekko Chart</title> <style> body { font: 10px sans-serif; } rect { stroke: #000; } svg { shape-rendering: crispEdges; } </style> <body> <script src="//d3js.org/d3.v3.min.js"></script> <script> var width = 800, height = 600, margin = 20; var x = d3.scale.linear() .range([0, width - 3 * margin]); var y = d3.scale.linear() .range([0, height - 2 * margin]); var z = d3.scale.category10(); var n = d3.format(",d"), p = d3.format("%"); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + 2 * margin + "," + margin + ")"); d3.json("data.json", function(error, data) { if (error) throw error; var offset = 0; // Nest values by cat2. We assume each cat2+cat1 is unique. var cat2s = d3.nest() .key(function(d) { return d.cat2; }) .entries(data); // Compute the total sum, the per-cat2 sum, and the per-cat1 offset. // You can use reduce rather than reduceRight to reverse the ordering. // We also record a reference to the parent cat2 for each cat1. var sum = cat2s.reduce(function(v, p) { return (p.offset = v) + (p.sum = p.values.reduceRight(function(v, d) { d.parent = p; return (d.offset = v) + d.value; }, 0)); }, 0); // Add x-axis ticks. var xtick = svg.selectAll(".x") .data(x.ticks(10)) .enter().append("g") .attr("class", "x") .attr("transform", function(d) { return "translate(" + x(d) + "," + y(1) + ")"; }); xtick.append("line") .attr("y2", 6) .style("stroke", "#000"); xtick.append("text") .attr("y", 8) .attr("text-anchor", "middle") .attr("dy", ".71em") .text(p); // Add y-axis ticks. var ytick = svg.selectAll(".y") .data(y.ticks(10)) .enter().append("g") .attr("class", "y") .attr("transform", function(d) { return "translate(0," + y(1 - d) + ")"; }); ytick.append("line") .attr("x1", -6) .style("stroke", "#000"); ytick.append("text") .attr("x", -8) .attr("text-anchor", "end") .attr("dy", ".35em") .text(p); // Add a group for each cat2. var cat2s = svg.selectAll(".cat2") .data(cat2s) .enter().append("g") .attr("class", "cat2") .attr("xlink:title", function(d) { return d.key; }) .attr("transform", function(d) { return "translate(" + x(d.offset / sum) + ")"; }); // Add a rect for each cat1. var cat1s = cat2s.selectAll(".cat1") .data(function(d) { return d.values; }) .enter().append("a") .attr("class", "cat1") .attr("xlink:title", function(d) { return d.cat1 + " " + d.parent.key + ": " + n(d.value); }) .append("rect") .attr("y", function(d) { return y(d.offset / d.parent.sum); }) .attr("height", function(d) { return y(d.value / d.parent.sum); }) .attr("width", function(d) { return x(d.parent.sum / sum); }) .style("fill", function(d) { return z(d.cat1); }); }); </script>
https://d3js.org/d3.v3.min.js