Published
Edited
Dec 21, 2020
Insert cell
Insert cell
Insert cell
myDomain2 = []
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);

const brush = d3.brushX()
.extent([[margin.left, margin.top], [width - margin.right, height - margin.bottom]])
// necessary to move this after to set the brush active selection at full range.
// keep commented
// .on("brush", brushed);

svg.append("g")
.call(xAxis);

svg.append("g")
.call(brush)
// set brush active selection
.call(brush.move, x.range());
// bind the "brush" event after the active selection is set
brush.on("brush", brushed);
function brushed(event) {
if (d3.event.sourceEvent.type === "brush") return;
const d0 = d3.event.selection.map(x.invert);
const d1 = d0.map(interval.round);

// If empty when rounded, use floor instead.
if (d1[0] >= d1[1]) {
d1[0] = interval.floor(d0[0]);
d1[1] = interval.offset(d1[0]);
}

d3.select(this).call(brush.move, d1.map(x));
}

return svg.node();
}
Insert cell
interval = d3.timeYear.every(1)
Insert cell
x = d3.scaleTime()
.domain(myDomain)
.rangeRound([margin.left, width - margin.right])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(g => g.append("g")
.call(d3.axisBottom(x)
.ticks(interval)
.tickSize(-height + margin.top + margin.bottom)
.tickFormat(() => null))
.call(g => g.select(".domain")
.attr("fill", "#ddd")
.attr("stroke", null))
.call(g => g.selectAll(".tick line")
.attr("stroke", "#fff")
.attr("stroke-opacity", d => d <= d3.timeDay(d) ? 1 : 0.5)))
.call(g => g.append("g")
.call(d3.axisBottom(x)
.ticks(d3.timeYear.every(2))
.tickPadding(0))
.attr("text-anchor", null)
.call(g => g.select(".domain").remove())
.call(g => g.selectAll("text").attr("x", 6)))
Insert cell
margin = ({top: 10, right: 0, bottom: 20, left: 0})
Insert cell
height = 120
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