'How to incorporate keys or dataframe column names in plotly express custom hover text?

Lost as I can be on how to control hover text with embedded data.

Non-dataframe scenario

In one case, I am passing a list of dicts to a plotly express (scatter) plot, having the shape:

list[dict[str, float]]

and I would like the hover text for each point to include its key from the dict inside my own domain-specific phrasing for the hover text.

When not tampering with the hover text, the default hover text showing up includes the key following the string "variable", and the x and y values being called "index" and "value" accordingly there in the default hover text. Obviously the x value is just the index of the dict from the list for input shaped as in my input type.

But incorporating these values with names bearing the semantics of the data seems to pose a challenge, as including something like follows does not really plug in (by substitution) anything but the x and y values in the percent prefix bracelets:

fig.update(data=[{'hovertemplate': 'distance: %{y} (class %{variable})'}])

For example, %{variable} will show as just the string as is, it will not substitute this string with the value of what the default hover text calls "variable".

How would I incorporate the "variable" value, as called in the default hover text, in my own hover text specification?

I went through numerous documentation pages where this is accomplished via plotly's non-express api or other ways which didn't seem to work for me. It's in general elusive to adapt any of the dataframe based solutions to my dataframe-sidestepping case. I wonder if there's an idiomatic way.

DataFrame based scenario

In another case, switching to dataframe input, I still battle to get the desired column name be recognized as, I wander in the plurality of ways to handle hover text and data for plotly:

fig = px.scatter(df, x='x', y='distance', color='class')
fig.update(data=[{'hovertemplate': 'distance: %{y} class %{class}'}])
fig.show()

%{class} in the above dataframe oriented approach, is obviously not the proper way to select the class column's value for the hover data. How would I bring in the value of the desired dataframe column name into the hover text?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source