KansaiRobot
KansaiRobot

Reputation: 10022

Plotly, Changing the hover text

I am trying to change the hover text in plotly. As an example there is

import plotly.graph_objects as go

fig = go.Figure(go.Scatter(
    x = [1,2,3,4,5],
    y = [2.02825,1.63728,6.83839,4.8485,4.73463],
    hovertemplate =
    '<i>Price</i>: $%{y:.2f}'+
    '<br><b>X</b>: %{x}<br>'+
    '<b>%{text}</b>',
    text = ['Custom text {}'.format(i + 1) for i in range(5)],
    showlegend = False))

fig.add_trace(go.Scatter(
    x = [1,2,3,4,5],
    y = [3.02825,2.63728,4.83839,3.8485,1.73463],
    hovertemplate = 'Price: %{y:$.2f}<extra></extra>',
    showlegend = False))

fig.update_layout(
    hoverlabel_align = 'right',
    title = "Set hover text with hovertemplate")

fig.show()

enter image description here

Can you see the part in blue where it says "trace 0". Where does that come from? If you hover in the red curve you will notice that something similar does not appear.

I want to reproduce this, so I want to understand where that is coming from

Upvotes: 3

Views: 4033

Answers (1)

Derek O
Derek O

Reputation: 19610

You can enable/disable the trace0, trace1,... text for each set of points by removing/adding the <extra></extra> tag. The documentation for hover text customization can be found here.

To make trace1 appear on your second set of points, remove the <extra></extra> tag.

import plotly.graph_objects as go

fig = go.Figure(go.Scatter(
    x = [1,2,3,4,5],
    y = [2.02825,1.63728,6.83839,4.8485,4.73463],
    hovertemplate =
    '<i>Price</i>: $%{y:.2f}'+
    '<br><b>X</b>: %{x}<br>'+
    '<b>%{text}</b>',
    text = ['Custom text {}'.format(i + 1) for i in range(5)],
    showlegend = False))

## Remove the extra tag
fig.add_trace(go.Scatter(
    x = [1,2,3,4,5],
    y = [3.02825,2.63728,4.83839,3.8485,1.73463],
    hovertemplate = 'Price: %{y:$.2f}',
    showlegend = False))

fig.update_layout(
    hoverlabel_align = 'right',
    title = "Set hover text with hovertemplate")

fig.show()

enter image description here

Upvotes: 2

Related Questions