Public
Edited
Dec 14, 2018
1 star
Insert cell
Insert cell
chart = {
const width = 950,
height = 500,
margin = 50;

const x = d3.scaleLinear()
.range([0, width - 3 * margin]);

const y = d3.scaleLinear()
.range([0, height - 2 * margin]);

const z = d3.scaleOrdinal(['#e66101','#fdb863','#b2abd2','#5e3c99']);

const n = d3.format(",d"),
p = d3.format(".0%");

const svg = d3.select(DOM.svg(width, height));
const container = svg
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + 2 * margin + "," + margin + ")")
.style("font-family", "sans-serif")
.style("font-size", "10px")
.style("shape-rendering", "crispEdges");

const offset = 0;

// Nest values by segment. We assume each segment+market is unique.
let segments = d3.nest()
.key(d => d.segment)
.entries(data);

// Compute the total sum, the per-segment sum, and the per-market offset.
// You can use reduce rather than reduceRight to reverse the ordering.
// We also record a reference to the parent segment for each market.
const sum = segments.reduce((v, p) => (p.offset = v) + (p.sum = p.values.reduceRight((v, d) => {
d.parent = p;
return (d.offset = v) + d.value;
}, 0))
,0);

// Add x-axis ticks.
const xtick = container.selectAll(".x")
.data(x.ticks(10))
.enter().append("g")
.attr("class", "x")
.attr("transform", d => "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.
const ytick = container.selectAll(".y")
.data(y.ticks(10))
.enter().append("g")
.attr("class", "y")
.attr("transform", d => "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 segment.
segments = container.selectAll(".segment")
.data(segments)
.enter().append("g")
.attr("class", "segment")
.attr("xlink:title", d => d.key)
.attr("transform", d => "translate(0," + y(d.offset / sum) + ")");

// Add a rect for each market.
const markets = segments.selectAll(".market")
.data(d => d.values)
.enter().append("a")
.attr("class", "market")
.attr("xlink:title", d => d.market + " " + d.parent.key + ": " + n(d.value))
.append("rect")
.attr("x", d => x(d.offset / d.parent.sum))
.attr("width", d => x(d.value / d.parent.sum))
.attr("height", d => y(d.parent.sum / sum))
.style("fill", d => z(d.market))
.style("stroke", "#000");

return svg.node();
}
Insert cell
Insert cell
d3 = require('d3@5')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more