How to display Latex in hover text?

According to the documentation(Latex in Python), Latex formulas are currently supported on the title, legend, and tick, but it seems there is no Latex formula on the hover text, and I would like to know if there is a solution for this.

Thanks to everyone, who is willing to spend his time on my issue.

Example 1:
The formula is not shown in the red box.

import plotly.graph_objs as go

fig = go.Figure()
fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4],
    y=[1, 4, 9, 16],
    name=r'$\alpha_{1c} = 352 \pm 11 \text{ km s}^{-1}$'
))
fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4],
    y=[0.5, 2, 4.5, 8],
    name=r'$\beta_{1c} = 25 \pm 11 \text{ km s}^{-1}$'
))
fig.update_layout(
    xaxis_title=r'$\sqrt{(n_\text{c}(t|{T_\text{early}}))}$',
    yaxis_title=r'$d, r \text{ (solar radius)}$'
)
fig.show()

Example 2:
\gamma is not shown correctly at the red box

import plotly.express as px

df = px.data.gapminder().query("continent=='Americas'")
ls_first4 = df.country.unique()[:5]
df = df.loc[df.country.isin(ls_first4)]

fig = px.scatter(df, 
                 x="year", 
                 y="lifeExp",
                 symbol = "country",
                 color="country",
                 hover_name="country",
                 hover_data={"country": False},
                 title="year-lifeExp"
                )
fig.update_traces(
        text=[r"$\gamma$" for i in range(12)],
        hovertemplate=r"Year: %{x} %{text} min"
)
fig.show()

To insert Latex text in hovertemplate, I’m exploiting a jupyter notebook (or jupyter lab) feature. Namely, if you write in a notebook cell, \beta followed by a click on the keyboard tab, you’ll get the LaTeX β. Copy this char and paste it in the hovertemplate definition.
(in fact what you are copying is the unicode for β) In the attached image I inserted βₜ, writing in a notebook cell
\beta<tab>\_<tab>. After the last <tab>, a pop-up window displays
all digits 0-9 and letters a-z, to select one as a subscript for β.

import plotly.graph_objects as go
import numpy as np
fig=go.Figure(go.Scatter(x=[1,2,3,4,5], y=np.random.randint(4,9, size=5), 
                         hovertemplate="βₜ:  %{y}<extra></extra>"))
fig.update_layout(width=600, height=350)


Always when a text as "$\beta_t$" is not displayed correctly on a plot, it is recommended to use the unicode for each LaTeX char.

1 Like

Very good method, this method can solve most of the problems. But I have another problem, when displaying division, only 1/γ is displayed, not \frac{1}{\gamma} :thinking:.

https://superuser.com/questions/1491773/what-unicode-character-is-used-to-describe-a-horizontal-fraction-bar
1 Like