Published
Edited
Jan 26, 2022
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
d3 = require("d3@5", "d3-delaunay@5")
// d3 = require("d3@5", "d3-voronoi@1") // This is what Agnes Chang's notebook uses instead
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
scatterplotWithVoronoiTooltips = {
const svg = d3.create("svg")
.style("font-family", "Work Sans, sans-serif")
.attr("viewBox", [0, 0, width, height]);
const exerciseColorMap = new Map([["Bike", "#8242a8"], ["Run", "#ff1493"], ["Walk", "#FFCE1E"]]);
svg.append("g")
.call(xAxis);

svg.append("g")
.call(yAxis);
// chart title
svg.append("text")
.attr("transform", `translate(0, 0)`)
.attr("dy", "1em")
.attr("text-anchor", "start")
.style("fill", "#202630")
.style("font-size", 18)
.html("Exercise in April–May 2020");

// POINTS
svg.append("g")
.attr("class", "points")
.selectAll("circle")
.data(data.filter(d => d.y > 1))
.join("circle")
.attr("stroke-width", "3")
.attr("opacity", 0.7)
.attr("stroke", d => exerciseColorMap.get(d['typeOfExercise']))
.attr("fill", d => exerciseColorMap.get(d['typeOfExercise']))
.attr("transform", d => `translate(${x(d.x)},${y(d.y)})`)
.attr("r", 3);
const voronoi = d3.Delaunay
.from(data, d => x(d.x), d => y(d.y))
.voronoi([margin.left, margin.top, width - margin.right, height - margin.bottom]); // ensures voronoi is limited to the chart area

svg.append("g")
.attr("class", "voronoiWrapper")
.selectAll("path")
.data(data)
.join("path")
.attr("opacity", 0.5)
// .attr("stroke", "#ff1493") // Hide overlay
.attr("fill", "none")
.style("pointer-events", "all")
.attr("d", (d,i) => voronoi.renderCell(i))
.on("mouseover", (d, i) => {
if (d.y > 1) {
svg.append('g')
.attr("class", "tooltip")
.attr("transform", `translate(${x(d.x)},${y(d.y)})`)
.call(popover, `Amount: ${d.y.toLocaleString(undefined, {style: "decimal"})}
${d.x.toLocaleString(undefined, {month: "short", day: "numeric", year: "numeric"})}
${d.typeOfExercise}`)
}
})
.on("mouseout", () => svg.selectAll('.tooltip').remove());

return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
data[0]
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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