function barChart(
data,
{
x = "x",
y = "y",
grouping,
sort,
reverse = false,
width,
height,
yLabel,
yTickFormat = "s",
xLabel,
xTickFormat,
groupingLabel = null,
fill,
scheme = schemeCategory10
} = {}
) {
const xAccessor = typeof x === "function" ? x : (d) => d[x];
const yAccessor = typeof y === "function" ? y : (d) => d[y];
const gAccessor =
typeof grouping === "function"
? grouping
: typeof grouping == "string"
? (d) => d[y]
: grouping;
const sortAccessor = sort === "y" ? xAccessor : xAccessor;
let domain = [...new Set(data.map(sortAccessor))];
if (sort) {
domain = [...new Set(d3.sort(data, sortAccessor).map(xAccessor))];
}
if (reverse) {
domain = domain.slice().reverse();
}
if (grouping == null) {
return Plot.plot({
width,
height,
x: { type: "band", domain, label: xLabel, tickFormat: xTickFormat },
y: { grid: true, label: yLabel, tickFormat: yTickFormat },
marks: [
Plot.ruleY([0]),
Plot.barY(data, {
x: xAccessor,
y: yAccessor,
fill: fill || scheme[0] || main.blue["700"],
title: xAccessor
})
]
});
}
const groups = [...new Set(data.map((d) => d[grouping]))];
return Plot.plot({
padding: 0.01,
width,
height,
color: { domain, range: scheme, legend: true },
x: {
domain,
axis: null,
tickFormat: xTickFormat
},
y: { grid: true, label: yLabel, tickFormat: yTickFormat },
fx: {
label: groupingLabel,
domain: groups,
padding: 0.1
},
facet: { data, x: grouping },
marks: [
Plot.ruleY([0]),
Plot.barY(data, {
x: xAccessor,
y: yAccessor,
fill: xAccessor
})
]
});
}