Public
Edited
Apr 3, 2023
Insert cell
Insert cell
Insert cell
{
const width = 400;
const height = 400;
const count = 500;
const values = Array.from({length: count}, (_, i) => ({ x: Math.random() * width, y: Math.random() * height, i: i }));

// Container div for SVG element and tooltip div element.
const container = d3.create("div");

// SVG.
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height);

// SVG border.
svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.style("stroke", "black")
.style("fill", "none")
.style("stroke-width", 1);
// Points.
const dots = svg
.append("g")
.style("fill", "steelblue")
.selectAll("dot")
.data(values)
.join("circle")
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("r", 5)
.style("opacity", 0.75);

// Tooltip div.
const tooltip = container.append("div")
.style("display", "none")
.style("background", "rgba(69,77,93,.9)")
.style("border-radius", ".2rem")
.style("color", "#fff")
.style("padding", ".6rem")
.style("position", "absolute")
.style("text-overflow", "ellipsis")
.style("white-space", "pre")
.style("line-height", "1em")
.style("z-index", "300");

// Pointer events to show / hide tooltip.
dots
.on("pointerenter pointermove", (e) => {
// Get pointer position relative to svg.
const xpos = d3.pointer(e, svg.node())[0];
const ypos = d3.pointer(e, svg.node())[1];

// Get selected datum.
const d = d3.select(e.target).datum();

// Set tooltip visible and update text.
tooltip
.style("display", null)
.html(`index: ${d.i}<br>x: ${d.x}<br>y: ${d.y}`);

// Align tooltip position.
const { width: textw, height: texth } = tooltip.node().getBoundingClientRect();
tooltip
.style("left", (xpos - textw / 2) + "px")
.style("top", (ypos - texth - 5) + "px");
})
.on("pointerleave", (e) => {
// Hide tooltip.
tooltip.style("display", "none");
});

// Append SVG element to container.
container.append(() => svg.node());
return container.node()
}
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