Plotly - hovertemplate two columns

Viewed 31

How to format the hover template to align the second column, please? Spacing is not enough as you can see in figure.

import plotly.express as px
import pandas as pd
import numpy as np

r = np.random.RandomState(42)
df = pd.DataFrame(
    {
        **{"x": np.linspace(0, 1, 10), "y": r.uniform(8, 9, 10)},
        **{c: r.uniform(i, i + 1, 10) for i, c in enumerate("ABCDE")},
    }
)

fig = px.scatter(df, x="x", y="y", hover_data={c: True for c in df.columns})

fig.update_traces(
    hovertemplate="<br>".join(
        [
            "<b>TT:</b>                              %{customdata[0]}",
            "<b>A: </b>                              %{x:.3f} deg",
            "<b>CCCCC: </b>                    %{y:.3f} deg<extra></extra>",  # extra delete the name next to the hover
            "<b>K: </b>                              %{customdata[2]:.3f} deg",
            "<b>LLLLLLLLLLLLLL:</b>   %{customdata[1]:.3f} deg",
        ]
    )
)

fig.show()

enter image description here

1 Answers
  • Have created MWE.
  • use none breaking spaces
  • use fixed width font
import plotly.express as px
import pandas as pd
import numpy as np

# construct figure for MWE
r = np.random.RandomState(42)
df = pd.DataFrame(
    {
        **{"x": np.linspace(0, 1, 10), "y": r.uniform(8, 9, 10)},
        **{c: r.uniform(i, i + 1, 10) for i, c in enumerate("ABCDE")},
    }
)

fig = px.scatter(df, x="x", y="y", hover_data={c: True for c in df.columns})

# use none breaking spaces and fixed width font
fig.update_traces(
    hovertemplate="<br>".join(
        [
            s.replace(" ", "&nbsp;")
            for s in [
                "<b>TT:</b>               %{customdata[0]}",
                "<b>A: </b>               %{x:.3f} deg",
                "<b>CCCCC: </b>           %{y:.3f} deg<extra></extra>",  # extra delete the name next to the hover
                "<b>K: </b>               %{customdata[2]:.3f} deg",
                "<b>LLLLLLLLLLLLLL:</b>   %{customdata[1]:.3f} deg",
            ]
        ]
    )
).update_layout(hoverlabel_font_family="Courier")

enter image description here

Related