Python Dash: add a point to plot that follows the plot according to x-value given

I want to create a plot in Plotly with 2 features:

  1. It is a scatterplot/lineplot that plots a list of y vs list of x variables.
  2. It has a 2nd dot whose x-value is controlled by a slider (range is constrained to x variables list). This dot will follow the plot in 1.

I do not know how to implement the 2nd feature.

This is my code. The first trace handles the 1st plot, the second trace should handle the 2nd dot:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># library imports
import dash
from dash import html, Input, Output, dcc
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import pandas as pd
# data
df = pd.DataFrame(
data = {
"varA": [1.5, 2.3, 3.1, 4.4954],
"varB": [6.1232, 4.4343, 8.432, 5.39],
}
)
# app info
style_sheets = [
dbc.themes.BOOTSTRAP
]
app = dash.Dash(__name__, external_stylesheets=style_sheets)
app.layout = html.Div(
[
dcc.Graph("graph"),
dcc.Slider(
min = min(df["varA"].tolist()),
max = max(df["varA"].tolist()),
value = 0,
id="slider"
)
]
)
# Callback
@app.callback(
Output("graph", "figure"),
[Input("slider", "value")]
)
def create_graph(slider_input):
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=df["varA"],
y=df["varB"],
mode='lines+markers', # add markers
marker=dict(size=10) # marker size
)
)
# Given value x, find a
closest_value = df['varA'].iloc[(df['varA'] - slider_input).abs().argsort()[:1]].values[0]
print(slider_input)
print(closest_value)
index_of_x = df.index[df['varA'] == closest_value].tolist()[0]
corresponding = df.iloc[index_of_x]['varB']
# Add the dot whose position changes based on the slider input
fig.add_trace(
go.Line(
x=[slider_input],
y=[corresponding],
mode='markers',
marker=dict(color='red', size=12),
name='Slider Dot'
)
)
return fig
if __name__ == '__main__':
app.run_server(debug=False)
</code>
<code># library imports import dash from dash import html, Input, Output, dcc import dash_bootstrap_components as dbc import plotly.graph_objs as go import pandas as pd # data df = pd.DataFrame( data = { "varA": [1.5, 2.3, 3.1, 4.4954], "varB": [6.1232, 4.4343, 8.432, 5.39], } ) # app info style_sheets = [ dbc.themes.BOOTSTRAP ] app = dash.Dash(__name__, external_stylesheets=style_sheets) app.layout = html.Div( [ dcc.Graph("graph"), dcc.Slider( min = min(df["varA"].tolist()), max = max(df["varA"].tolist()), value = 0, id="slider" ) ] ) # Callback @app.callback( Output("graph", "figure"), [Input("slider", "value")] ) def create_graph(slider_input): fig = go.Figure() fig.add_trace( go.Scatter( x=df["varA"], y=df["varB"], mode='lines+markers', # add markers marker=dict(size=10) # marker size ) ) # Given value x, find a closest_value = df['varA'].iloc[(df['varA'] - slider_input).abs().argsort()[:1]].values[0] print(slider_input) print(closest_value) index_of_x = df.index[df['varA'] == closest_value].tolist()[0] corresponding = df.iloc[index_of_x]['varB'] # Add the dot whose position changes based on the slider input fig.add_trace( go.Line( x=[slider_input], y=[corresponding], mode='markers', marker=dict(color='red', size=12), name='Slider Dot' ) ) return fig if __name__ == '__main__': app.run_server(debug=False) </code>
# library imports
import dash
from dash import html, Input, Output, dcc
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import pandas as pd

# data
df = pd.DataFrame(
    data = {
        "varA": [1.5, 2.3, 3.1, 4.4954],
        "varB": [6.1232, 4.4343, 8.432, 5.39],
    }
)
# app info
style_sheets = [
    dbc.themes.BOOTSTRAP
]
app = dash.Dash(__name__, external_stylesheets=style_sheets)
app.layout = html.Div(
    [
        dcc.Graph("graph"),
        dcc.Slider(
            min = min(df["varA"].tolist()),
            max = max(df["varA"].tolist()),
            value = 0,
            id="slider"
        )
    ]
)

# Callback
@app.callback(
    Output("graph", "figure"),
    [Input("slider", "value")]
)
def create_graph(slider_input):
    fig = go.Figure()
    fig.add_trace(
        go.Scatter(
            x=df["varA"],
            y=df["varB"],
            mode='lines+markers',  # add markers
            marker=dict(size=10)   # marker size
        )
    )

    # Given value x, find a 
    closest_value = df['varA'].iloc[(df['varA'] - slider_input).abs().argsort()[:1]].values[0]
    print(slider_input)
    print(closest_value)
    index_of_x = df.index[df['varA'] == closest_value].tolist()[0]

    corresponding = df.iloc[index_of_x]['varB']

    # Add the dot whose position changes based on the slider input
    fig.add_trace(
        go.Line(
            x=[slider_input],
            y=[corresponding],
            mode='markers',
            marker=dict(color='red', size=12),
            name='Slider Dot'
        )
    )
    return fig


if __name__ == '__main__':
    app.run_server(debug=False)

This is the output plot. I want the red dot to traverse the blue line according to the slider x value.

Output plot

Thank you in advance.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật