HTML Overlays in Plotly.js

HTML Hover Lines for Plotly.js Chart

I’ve talked about several features and limitations of Plotly.js before. It’s a very capable framework but I’ve found a number of important limitations. One in particular has come up again and again: structuring and styling hover overlays. By default, Plotly.js hover tooltips look something like this:

Plotly.js Guide: Hover Text and Formatting

While you get a few basic controls: color, background color, and cardinal position, it leaves a lot to be desired. You could go the route of modifying or styling the SVG elements generated on hover, but that’s also quite limited. The most robust solution I’ve found is to create a chart overlay using HTML, with the ability to style and modify using CSS and JS. To that effect, I’ve created a vanilla JS proof of concept:

The idea is to place the Plotly chart into a container and position an HTML element overlaying the chart.

Chart Overlay

Then listen for the plotly_hover and plotly_unhover events to position elements within the overlay. Here I’ve positioned lines extending well beyond the overlay, but they get constrained to the correct size because I’ve applied overflow: hidden to the overlay.

As a note of caution: you’ll need to handle browser resize events to correctly size and position the overlay should the chart dimensions change.