How to add Hovering Annotation for the Y value of a Horizontal Line in Plotly created using figure.add_shape(type='line')

Solution 1:

  • it's straight forward to replace layout shapes with traces
  • this shows this within the bounds of your sample code, where I had to imply your data started at epoch and your line would be for only 4 milliseconds, so I extended it to 4.5 hrs
import plotly.graph_objects as go
import pandas as pd
from datetime import datetime
import numpy as np

# setup all necessary variables and MWE could not be provide :-(
stocks = pd.read_csv(
    "https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv",
    parse_dates=["Date"],
)
$ rebase data to start at epoch as sample code implies it does
stocks["Date"] = pd.date_range("1-jan-1970", freq="1Min", periods=len(stocks))
Date = "Date"
Open = "AAPL.Open"
High = "AAPL.High"
Low = "AAPL.Low"
Close = "AAPL.Close"


fig = go.Figure(
    data=[
        go.Candlestick(
            opacity=0.9,
            x=stocks[Date],
            name="X",
            open=stocks[Open],
            high=stocks[High],
            low=stocks[Low],
            close=stocks[Close],
        ),
    ]
)


# replace this line of code.  but it's implications are weird.  line for 4 milliseconds just after epoch
# fig.add_shape(type="line", x0=1, x1=2, y0=5, y1=5,line_width=1.5, line_dash="dot", line_color="red")
# replace with this - let's make it 4.5hrs long
fig.add_shape(
    type="line",
    x0=1,
    x1=1.5 * 10 ** 7,
    y0=5,
    y1=5,
    line_width=1.5,
    line_dash="dot",
    line_color="red",
)
# equivalend as a trace, and now have hover...
fig.add_traces(
    go.Scatter(
        x=np.linspace(1, 1.5 * 10 ** 7, 100),
        y=np.repeat([5], 100),
        mode="lines",
        line_dash="dot",
        line_color="red",
        showlegend=False,
    )
)

enter image description here