python-3.xplotlyonhover

How do I add vertical moving hover line to my plotly chart


I am trying to achieve what is done here: https://www.quantalys.com/Fonds/120955 with javascript in python plotly. I want to add the hover vertical line and the red annotation on the x axis. I have done some searching on goolgle but I couldn't find the the answer I'm looking for. My current chart looks like this:

trace1 = go.Scatter(
x = df1.x,
y = df1.y,
name = "M&G OPTIMAL INCOME FD EUR AH ACC",
hoverinfo= 'name',
opacity=0.7,
mode = 'lines',
    line = dict(
    color = ('rgb(2, 12, 245)'),
    width = 1,
    ), 
)
trace2 = go.Scatter(
x = df2.x,
y = df2.y,
opacity=0.7,
name = "Alloc Flexible Prudent Monde",
hoverinfo= 'name',
mode = 'lines',
    line = dict(
    color = ('rgb(67, 45, 24)'),
    width = 1,
    )
)
trace3 = go.Scatter(
x = df3.x,
y = df3.y,
name = "25% MSCI World + 75% ML Global",
hoverinfo= 'name',
mode = 'lines',
opacity=0.7,
line = dict(
    color = ('rgb(205, 12, 24)'),
    width = 1,
    )
)

layout = go.Layout(

xaxis=dict(        
    showline=True,
    showgrid=True,
    showticklabels=True,
    linecolor='rgb(204, 204, 204)',
    linewidth=2,
    mirror=True,
),
yaxis=dict(
            showline=True,
    showgrid=True,
    showticklabels=True,
    linecolor='rgb(204, 204, 204)',
    linewidth=2,
    mirror=True,
),
showlegend=True,

)

data= [trace1, trace2,trace3]
fig = dict(data=data, layout=layout)
iplot(fig, filename='line-mode')

Solution

  • Add this to your layout definition.

    showlegend = True,
    hovermode  = 'x'
    

    Add this to your xaxis definition.

    showspikes = True,
    spikemode  = 'across',
    spikesnap = 'cursor',
    showline=True,
    showgrid=True,
    ...
    

    And add this to your layout definition:

    spikedistance =  -1,
    xaxis=dict(...  
    
    

    Please refer to this post and the documentation by plotly. :)

    EDIT

    You ask for the x-axis lable. Please use

    spikemode  = 'across+toaxis'
    

    Additionally I would suggest to use

    spikedash = 'solid'
    

    because it is better fitting your example.