Search code examples
pythonplotlyplotly-python

update figure add hline with sliders Plotly Python


Hello guys i need help i have a piece of code that adds a list of horizontal lines to a Plotly figure in python. i want to change the code to were we will use a slider to add the horizontal lines to the figure and relayout it. As the slider moves right more horizontal lines will be added to the figure when the slider moves left the horizontal lines will be removed from the figure. Below is the bit of my code so far

for v in range(len(sortadlist)):
        fig.add_hline(y=sortadlist[v][0], line_color='brown', line_width=1.5, row=1, col=1)
        fig.add_shape(type="rect",
                      y0=round(sortadlist[v][0],2)-.3, y1=round(sortadlist[v][0],2)+.3, x0=-1, x1=len(df),
                      fillcolor="darkcyan",
                      opacity=0.15)

All the code above does is loop through a list of numbers and uses the fig.add_hline to add the horizontal line to the figure. I need help creating a slider that will add the horizontal lines to the figure enter image description here

This is how the figure currently looks i want a slider to help with adding more horizontal lines to the figure and remove them also


Solution

  • Since the entire code is not available, the sample data was handled by obtaining the company's stock price. First of all, horizontal lines and shapes do not have a show/hide attribute, so they are not compatible with sliders. So I have created a code to draw a line according to the appropriate price list in the line chart of the scatter chart. Once the line chart is hidden, the first line chart is made visible. The structure of the graph is a candlestick with 6 lines and the candlestick is always displayed. A loop process is used to create a list of lines to be shown or hidden.

    import yfinance as yf
    import plotly.graph_objects as go
    import numpy as np
    
    df = yf.download("AAPL", start="2022-01-01", end="2023-01-01", progress=False)
    df.reset_index(inplace=True)
    
    pricelist = np.arange(130,190,10)
    
    fig = go.Figure()
    fig.add_trace(go.Candlestick(x=df['Date'],
                                 open=df['Open'],
                                 high=df['High'],
                                 low=df['Low'],
                                 close=df['Close'],
                                 name='AAPL'
                                )
                 )
    
    fig.add_hrect(y0=df['Close'].median()-10,
                  y1=df['Close'].median()+10, 
                  annotation_text="Median+-10",
                  annotation_position="top right",
                  fillcolor="darkcyan",
                  opacity=0.25,
                  line_width=0)
    
    for p in pricelist:
        fig.add_trace(go.Scatter(x=df['Date'],
                                 y=[p]*len(df['Date']),
                                 line_color='blue',
                                 name=str(p),
                                 showlegend=False,
                                 visible=False,
                                )
                     )
    fig.data[1].visible = True
    
    steps = []
    for i in np.arange(1,len(fig.data)):
        step = dict(
            method="update",
            args=[{"visible": [False] * len(fig.data)},
                  {"title": "Price lines: " + str(pricelist[i-1])}],
            label=str(pricelist[i-1])
        )
        step["args"][0]["visible"][0] = True
        step["args"][0]["visible"][i] = True
        steps.append(step)
    
    sliders = [dict(
        active=10,
        currentvalue={"prefix": "Price: "},
        pad={"t": 50},
        steps=steps
    )]
    
    fig.update_layout(
        sliders=sliders
    )
    
    fig.update_layout(height=600, xaxis_rangeslider_visible=False)
    fig.show()
    

    enter image description here