简体   繁体   中英

How to obtain Click Event Coordinate Data on Plotly Dash Graph in Python?

I've tried navigating around the web for a solution to this problem, but have had no luck. The closest solution I found was this , however, it's in R and I've been trying to look for a solution in Python for this these past twos days.

I've already messed with Plotly Dash's documentation here on Interactive Graphing and the clickData and hoverData seems to only output coordinate data on actual data points on the graph that are clicked/hovered over on. My goal is obtain a pair of x,y coordinate through two mouse clicks on the graph, so that I am able to draw a line on the graph using that pair of coordinates. However, it seems Plotly's Dash Interactive Graphing is limited in its ability to provide mouse coordinate data that are not on actual data points. Is there any work around to this or an obvious solution / part of the documentation that I missed?

  • you can create an additional trace of transparent points that are scattered uniformly across the figure
  • then it's a simple case of using clickData callback
  • full code below
import numpy as np
import pandas as pd
import plotly.express as px
import math, json
import dash
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash

GS = 100
fig = px.line(
    x=np.linspace(0, 1, 300), y=(np.sin(np.linspace(0, math.pi * 3, 300)) / 2) + 0.5
).add_traces(
    px.scatter(
        x=np.repeat(np.linspace(0, 1, GS), GS), y=np.tile(np.linspace(0, 1, GS), GS)
    )
    .update_traces(marker_color="rgba(0,0,0,0)")
    .data
)

# Build App
app = JupyterDash(__name__)
app.layout = dash.html.Div(
    [dash.dcc.Graph(id="graph", figure=fig), dash.html.Div(id="where")]
)


@app.callback(
    Output("where", "children"),
    Input("graph", "clickData"),
)
def click(clickData):
    if not clickData:
        raise dash.exceptions.PreventUpdate
    return json.dumps({k: clickData["points"][0][k] for k in ["x", "y"]})


# Run app and display result inline in the notebook
app.run_server(mode="inline")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM