hbar_stack_norm = (data, options={}) => {
if (data.length == 0) throw new Error('no data; nothing to represent');
const {
color_scheme_provider = d3.interpolateSpectral,
margin = {top: 20, right: 20, bottom: 10, left: 50},
chart_width = width,
chart_height = (data.length * 25) + margin.top + margin.bottom,
} = options;
if (!data.columns) data.columns = Object.keys(data[0]);
const series_labels = data.columns.slice(1);
const color_scheme = Array(series_labels.length).fill(0).map((v,i,a) => color_scheme_provider((i+1)/a.length));
const x = d3.scaleLinear()
.range([margin.left, chart_width - margin.right]);
const y = d3.scaleBand()
.domain(data.map(d => d.name))
.range([margin.top, chart_height - margin.bottom])
.padding(0.08);
const xAxis = g => g
.attr("transform", `translate(0,${margin.top})`)
.call(d3.axisTop(x).ticks(chart_width / 100, "%"))
.call(g => g.selectAll(".domain").remove());
const yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).tickSizeOuter(0))
.call(g => g.selectAll(".domain").remove());
const formatPercent = d3.format(".1%");
const formatValue = x => isNaN(x) ? "N/A" : x.toLocaleString("en");
const series = d3.stack()
.keys(series_labels)
.offset(d3.stackOffsetExpand)
(data)
.map(d => (d.forEach(v => v.key = d.key), d));
const color = d3.scaleOrdinal()
.domain(series.map(d => d.key))
.range(color_scheme)
.unknown("#fcc");
const svg = d3.create("svg")
.attr("width", chart_width)
.attr("height", chart_height);
svg.append("g")
.selectAll("g")
.data(series)
.enter().append("g")
.attr("fill", d => color(d.key))
.selectAll("rect")
.data(d => d)
.join("rect")
.attr("x", d => x(d[0]))
.attr("y", d => y(d.data.name))
.attr("width", d => x(d[1]) - x(d[0]))
.attr("height", y.bandwidth())
.append("title")
.text(d => `${d.data.name} ${d.key}\n${formatPercent(d[1] - d[0])} (${formatValue(d.data[d.key])})`);
svg.append("g")
.call(xAxis);
svg.append("g")
.call(yAxis);
return svg.node();
}