240 words
1 minute
Wider tooltip areas for Observable Plot

Wider tooltip areas for Observable Plot#

In this Observable notebook I’m plotting a line on a chart, but I want to provide tooltips showing the exact value at any point on the line.

Observable Plot (on desktop at least) can do that using the title mark property. But… if a line is only 1 pixel wide actually triggering a tooltip requires pin-point accuracy.

I figured out a workaround: render the same line twice - once with a tooltip and a very wide line length set to a low opacity, and then again as a solid thin black line.

Here’s what that looks like in JavaScript code for a cell:

Plot.plot({
marks: [
// This mark exists just for the tooltip - hence why it is wider and almost invisible
Plot.line(points, {
x: "date",
y: "users",
// Function to generate the text shown on the tooltip:
title: (d) => d.date.toLocaleString() + " - " + d.users.toLocaleString(),
strokeWidth: 12,
opacity: 0.01
}),
// This mark displays with the default stroke of a single pixel wide black line
Plot.line(points, {
x: "date",
y: "users"
})
],
})

The final effect looks like this:

CleanShot 2022-11-21 at 13 55 17@2x

Covering the whole vertical area#

Fil on Twitter suggests this improvement, which extends the hover area for each point on the line to the full height of the chart:

Plot.tickX(points, {
x: "date",
title: (d) => d.date.toLocaleString() + " - " + d.users.toLocaleString(),
strokeWidth: 12,
stroke: "white",
opacity: 0.01
})
Wider tooltip areas for Observable Plot
https://mranv.pages.dev/posts/wider-tooltip-areas-for-observable-plot/
Author
Anubhav Gain
Published at
2024-11-26
License
CC BY-NC-SA 4.0