Skip to main content

nearestHover

import { createSelection } from "@sportsdataverse/sdvplot";
import { linkSelection, nearestHover } from "@sportsdataverse/sdvplot/interact";
import * as d3 from "d3";

const rows = [
{ team: "KC", wins: 15, net_epa: 0.063 },
{ team: "BUF", wins: 13, net_epa: 0.19 },
{ team: "MIA", wins: 8, net_epa: -0.019 },
{ team: "LV", wins: 4, net_epa: -0.146 },
];
const x = d3.scaleLinear([0, 17], [30, 410]);
const y = d3.scaleLinear([-0.2, 0.2], [190, 10]);
const svg = d3.create("svg").attr("viewBox", "0 0 440 200").attr("width", 440);
svg
.selectAll("circle")
.data(rows)
.join("circle")
.attr("data-sdv-id", (d) => d.team) // the d3 way to stamp link ids
.attr("cx", (d) => x(d.wins))
.attr("cy", (d) => y(d.net_epa))
.attr("r", 5)
.attr("fill", "currentColor");
const node = svg.node() as SVGSVGElement;
const store = createSelection();
linkSelection(store, { figure: node, hover: false }); // highlight follows the store; nearestHover writes hover
nearestHover(node, store, {
points: rows.map((d) => ({ x: x(d.wins), y: y(d.net_epa), id: d.team })),
radius: 18,
label: (team) => ({ lines: [team, `net EPA/play ${rows.find((d) => d.team === team)?.net_epa}`] }),
});
node; // hover near a dot: within 18 px it lights and its tooltip shows

Tags: docstring · nearestHover. All sdvplot examples.