viewof chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);
const brush = d3
.brushX()
.extent([
[margin.left, 0],
[width - margin.right, height - margin.bottom]
])
.on("start brush end", brushed);
var histogram = d3
.histogram()
.value((d) => d[0])
.domain(x.domain())
.thresholds(x.ticks(80));
var bins = histogram(data);
var yHeight = y.range()[0] - y.range()[1];
var yHist = d3
.scaleLinear()
.range([yHeight, 0])
.domain([0, d3.max(bins, (d) => d.length)]);
const rects = svg
.selectAll(".histRect")
.data(bins)
.join("rect")
.attr("class", "histRect")
.attr("x", 1)
.attr("transform", function (d) {
return (
"translate(" + x(d.x0) + "," + (yHist(d.length) + margin.top) + ")"
);
})
.attr("width", function (d) {
return x(d.x1) - x(d.x0) - 1;
})
.attr("height", function (d) {
return yHeight - yHist(d.length);
})
.style("fill", color);
svg.append("g").call(xAxis);
svg
.append("text")
.attr("text-anchor", "start")
.attr("font-family", "sans-serif")
.attr("font-size", ".75em")
.attr("x", margin.left)
.attr("y", margin.top)
.attr("dx", ".5em")
.attr("dy", ".5em")
.text(title);
const dx = (x.range()[1] - x.range()[0]) / x.ticks().length;
const x0 = dx / 2 + margin.left;
svg
.append("g")
.call(brush)
.call(brush.move, [x0 - dx / 2, x0 + dx / 2])
.call((g) =>
g
.select(".overlay")
.datum({ type: "selection" })
.on("mousedown touchstart", beforebrushstarted)
);
function beforebrushstarted(event) {
const [[cx]] = d3.pointers(event);
const [x0, x1] = [cx - dx / 2, cx + dx / 2];
const [X0, X1] = x.range();
d3.select(this.parentNode).call(
brush.move,
x1 > X1 ? [X1 - dx, X1] : x0 < X0 ? [X0, X0 + dx] : [x0, x1]
);
}
function brushed(event) {
const selection = event.selection;
if (selection === null) {
rects.attr("opacity", 0.5);
} else {
const [x0, x1] = selection.map(x.invert);
rects.attr("opacity", (d) => (x0 <= d.x0 && d.x1 <= x1 ? 1 : 0.5));
svg.node().value = [x0, x1];
svg.node().dispatchEvent(new CustomEvent("input"));
}
}
return svg.node();
}