Get started with d3-brush CDN
BSD-3-Clause licensed
D3-brush: Data brushing library for D3.js, selects data points by brushing graphs.
Tags:- d3
- d3-module
- brush
- interaction
Stable version
Copied!
How to start using d3-brush CDN
// Import required D3 libraries
const d3 = require("d3@5");
const brush = require("https://cdn.cdnhub.io/d3-brush/3.0.0/d3-brush.min.js");
// Sample data
const data = [
{ date: new Date("2022-01-01"), value: 10 },
{ date: new Date("2022-01-02"), value: 15 },
{ date: new Date("2022-01-03"), value: 12 },
{ date: new Date("2022-01-04"), value: 18 },
{ date: new Date("2022-01-05"), value: 14 },
];
// Set up the SVG container
const svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 200);
// Set up scales
const x = d3.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([0, 500]);
const y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([180, 0]);
// Set up axes
const xAxis = d3.axisBottom(x);
const yAxis = d3.axisLeft(y);
// Add axes to the chart
svg.append("g")
.attr("transform", "translate(0,0)")
.call(xAxis);
svg.append("g")
.attr("transform", "translate(50,0)")
.call(yAxis);
// Add line to the chart
const line = d3.line()
.x(d => x(d.date))
.y(d => y(d.value));
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
// Set up brush
const brushX = d3.brushX()
.extent([[0, 0], [500, 180]])
.on("brush end", updateSelection);
// Add brush to the chart
svg.append("g")
.attr("class", "brush")
.call(brushX);
// Update selection on brush event
function updateSelection() {
const selection = d3.event.selection;
if (selection) {
const filteredData = data.filter(d => x(d.date) >= selection[0] && x(d.date) <= selection[1]);
updateChart(filteredData);
}
}
// Update chart with new data
function updateChart(data) {
x.domain(d3.extent(data, d => d.date));
line.x(d => x(d.date));
svg.select(".line").datum(data).attr("d", line);
svg.select(".brush").call(brushX.extent(selection));
}