✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🧬 Learn how to build RNA-Seq data apps with Python & Dash. Register for the May 20 Webinar!

Python Plotly: custom template with the express library and hover_data

I am showing data using the express library (here as an example, the iris dataset dataframe):

fix = px.scatter_3d(df, x="sepal_width", y="sepal_length", z="petal_length", color="species",
                 size='petal_length', hover_data=['petal_width', 'additionalcolumn1'])

By default the hover box for each data point, shows the values for x, y, z, color, size, plus what is in the list of columns for the “hover_data” keyword.

It is easy to specify an alternate template for the hover box with

fig.update_traces(hovertemplate=sometmpl)

However, I cannot figure out which variable names to use to refer to the data that already gets used in the default hover box via the color, size and hover_data parameters. I can use “%{x}” but “%{color}” or “%{hover_data}” is apparently not known.

The documentation I found about using a hover template here only shows how to use “${x}” as an example but does not tell how to access the other data, especially the one from “hover_data”.

Welcome to our Plotly community, @johann.petrak

Try using:

fig.update_traces(hovertemplate=
        "%{customdata[0]}"
)

customdata[0] refers to the first value inside the hover_data() - petal_length.
customdata[1] refers to the second value inside the hover_data() - additionalcolumn1
You can add more values inside your hover_data to refer to them

I hope that helps,
Adam

1 Like

Cool, thank you, that worked!

Bonus question: since the normal hover box by default shows the data specified for size, color as well, is it possible to access those series from the template or only if I add them again in the hover_data list?

That’s a good question. I’m not sure. If I find out, I’ll let you know.

OK, I found out that the variable used for the size can be included using %{marker.size} but that does not work in the same way for color.

But in any case, the hover_data field is very flexible so all I need can be done!

1 Like