Remove hover tooltip from added trace (add_scatter) but not original trace

I have a line chart where I only want the end of the line to be labeled. To do that, I’m using add_scatter() as shown in this stack overflow post. When using hovermode="x", how do I remove the tooltip only for the added trace?

# imports
import pandas as pd
import plotly.express as px

# data
df = px.data.stocks()
df = df.drop('AMZN', axis = 1)
colors = px.colors.qualitative.T10

# plotly
fig = px.line(df, 
                 x = 'date',
                 y = [c for c in df.columns if c != 'date'],
                 template = 'plotly_dark',
                 color_discrete_sequence = colors,
                 title = 'Stocks', 
             )

# move legend
fig.layout.legend.x = -0.3

# add traces for annotations and text for end of lines
for i, d in enumerate(fig.data):
    fig.add_scatter(x=[d.x[-1]], y = [d.y[-1]],
                    mode = 'markers+text',
                    text = d.y[-1],
                    textfont = dict(color=d.line.color),
                    textposition='middle right',
                    marker = dict(color = d.line.color, size = 12),
                    legendgroup = d.name,
                    showlegend=False)

fig.update_layout(hovermode="x")

fig.show()

I specifically want to use hovermode="x" so that all trace values are displayed and sorted, but only for the original lines, not the line-end marks.

In add_scatter() I’ve tried some things like hovermode=False and hovertemplate="" but I don’t believe these work with the add trace methods.

Also, the text is cut off at the end of the lines. Is there a way to prevent that?

I think hoverinfo='skip' could help, and you can update_layout with margin to prevent text cut off. Something as below:

# imports
import pandas as pd
import plotly.express as px

# data
df = px.data.stocks()
df = df.drop('AMZN', axis = 1)
colors = px.colors.qualitative.T10

# plotly
fig = px.line(df, 
                 x = 'date',
                 y = [c for c in df.columns if c != 'date'],
                 template = 'plotly_dark',
                 color_discrete_sequence = colors,
                 title = 'Stocks', 
             )

# move legend
fig.layout.legend.x = -0.3

# add traces for annotations and text for end of lines
for i, d in enumerate(fig.data):
    fig.add_scatter(x=[d.x[-1]], y = [d.y[-1]],
                    mode = 'markers+text',
                    text = d.y[-1],
                    textfont = dict(color=d.line.color),
                    textposition='middle right',
                    marker = dict(color = d.line.color, size = 12),
                    legendgroup = d.name,
                    showlegend=False, hoverinfo='skip')

fig.update_layout(hovermode="x", margin=dict(l=50, r=50, t=50, b=50))

fig.show()

2 Likes