Published
Edited
Nov 5, 2019
1 star
Insert cell
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
const brush = d3.brush()
.extent([[margin.left, margin.top], [width - margin.right, height - margin.bottom]])
.on("start brush end", brushed);

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

svg.append("g")
.call(yAxis);
svg.append("g")
.call(brush);

const gs = svg.append("g")
.attr("stroke-width", 1.5)
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("g")
.data(data)
.join("g")
.attr("transform", d => `translate(${x(d.x)},${y(d.y)})`)
.call(g => g.append("circle")
.attr("fill", "steelblue")
.attr("r", 3))
.call(g => g.append("text")
.attr("dy", "0.35em")
.attr("x", 7)
.text(d => d.name));
function brushed() {
const selection = d3.event.selection;
if (selection === null) {
gs.select("circle").attr("stroke", null);
} else {
const [p0, p1] = selection.map(d => [x.invert(d[0]), y.invert(d[1])]);
mutable selected = data.filter(d =>
p0[0] <= d.x && d.x <= p1[0] &&
p0[1] >= d.y && d.y >= p1[1] );
gs.select("circle").attr("stroke", d =>
p0[0] <= d.x && d.x <= p1[0] &&
p0[1] >= d.y && d.y >= p1[1]
? "red" : null);

}

}

return svg.node();
}
Insert cell
mutable selected = data;
Insert cell
height = 600
Insert cell
margin = ({top: 20, right: 30, bottom: 30, left: 40})
Insert cell
x = d3.scaleLinear()
.domain(d3.extent(data, d => d.x)).nice()
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain(d3.extent(data, d => d.y)).nice()
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x))
.call(g => g.select(".domain").remove())
.call(g => g.append("text")
.attr("x", width - margin.right)
.attr("y", -4)
.attr("fill", "#000")
.attr("font-weight", "bold")
.attr("text-anchor", "end")
.text(data.x))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 4)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
Insert cell
data = Object.assign(await d3.csv(await FileAttachment("mtcars.csv").url(), ({name, mpg: x, hp: y}) => ({name, x: +x, y: +y})), {x: "Miles per gallon", y: "Horsepower"})
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