1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Click Event on Data Point Plotly Python

Discussão em 'Python' iniciado por Stack, Outubro 3, 2024 às 16:42.

  1. Stack

    Stack Membro Participativo

    I have a simple Plotly Python example script that I am trying to figure out how to add a click callback event to.

    What I want to do for demonstration is to add a textbox in the upper right hand corner that will display the coordinates of the data point when I click on it. So far I have the following:

    import plotly.graph_objects as go

    # Replace these with your actual data
    data1_x = [1, 2, 3, 4, 5]
    data1_y = [2, 4, 5, 3, 1]
    data2_x = [1, 2, 3, 4, 5]
    data2_y = [3, 1, 4, 2, 5]
    data3_x = [1, 2, 3, 4, 5]
    data3_y = [5, 3, 1, 2, 4]

    # Create a figure
    fig = go.Figure()

    # Add traces
    fig.add_trace(go.Scatter(x=data1_x, y=data1_y, mode='markers', name='Data 1'))
    fig.add_trace(go.Scatter(x=data2_x, y=data2_y, mode='markers', name='Data 2'))
    fig.add_trace(go.Scatter(x=data3_x, y=data3_y, mode='markers', name='Data 3'))

    # Add a textbox to the top right corner
    fig.add_annotation(
    xref="paper", yref="paper",
    x=1.02, y=1.05,
    text="Click on a data point",
    showarrow=False,
    font=dict(size=12)
    )

    # Define the callback function
    def update_text(trace, points, state):
    if points:
    x = points[0].x
    y = points[0].y
    # Format the coordinates as a string
    coordinates = f"({x}, {y})"
    # Update the text of the annotation
    fig.annotations[0].update(text=f"Clicked point: {coordinates}")

    # Add the callback to the figure
    fig.update_layout(clickmode='event+select')
    fig.data[0].on_click(update_text)
    fig.data[1].on_click(update_text)
    fig.data[2].on_click(update_text)

    # Show the plot
    fig.write_html('./test_click.html')


    I can't seem to get this to work and it does not change the text box at all.

    Continue reading...

Compartilhe esta Página