gpt4 book ai didi

python - Dash中鼠标绘制图形数据的获取方法

转载 作者:行者123 更新时间:2023-12-05 03:17:33 28 4
gpt4 key购买 nike

所以我有这个简单的 python dash 应用程序,我在其中布置了一个图形和一个按钮。我的目标是:当我按下按钮时,我想检索已绘制的形状。

import plotly.graph_objects as go
import dash
from dash import html, dcc, Input, Output, State

app = dash.Dash(__name__)
fig = go.Figure()

app.layout = html.Div([
dcc.Graph(id = "graph-pic", className="graph-pic", figure=fig, config={'modeBarButtonsToAdd':['drawrect', 'eraseshape']}),
html.Button("Shape count", id = "shape-count-button")
])

fig.add_shape(editable=True, x0=-1, x1=0, y0=2, y1=3, xref='x', yref='y')

@app.callback(
Output("graph-pic", "figure"),
Input("shape-count-button", "n_clicks")
)
def on_shape_count_button_pressed(n_clicks):
trigger_id = dash.callback_context.triggered_id

if trigger_id == "shape-count-button":
print("Shape count: " + str(len(fig.layout.shapes)))
print(fig.layout.shapes)

return dash.no_update

if __name__ == "__main__":
app.run_server()

Dash app当我按下按钮时,它只打印我通过代码添加的第一个形状...而不是我使用绘制矩形工具在图形上绘制的形状。

输出:

Shape count: 1
(layout.Shape({
'editable': True, 'x0': -1, 'x1': 0, 'xref': 'x', 'y0': 2, 'y1': 3, 'yref': 'y'
}),)

如有任何提示,我们将不胜感激!

最佳答案

你应该使用relayout_data来检测图形上所有绘制的形状,然后你可以像你一样解析所需的数据:

import dash
import json
import plotly.graph_objects as go
from dash import html, dcc, Input, Output, State

app = dash.Dash(__name__)
fig = go.Figure()

app.layout = html.Div([
dcc.Graph(id = "graph-pic", className="graph-pic", figure=fig, config={'modeBarButtonsToAdd':['drawrect', 'eraseshape']}),
html.Button("Shape count", id = "shape-count-button"),
html.Div(id="text")
])

fig.add_shape(editable=True, x0=-1, x1=0, y0=2, y1=3, xref='x', yref='y')

@app.callback(
Output("text", "children"),
Input("shape-count-button", "n_clicks"),
Input("graph-pic", "relayoutData"),
)
def on_shape_count_button_pressed(n_clicks, relayout_data):

trigger_id = dash.callback_context.triggered_id

if trigger_id == "shape-count-button":
text_lst = "Shape count: " + str(len(fig.layout.shapes))
text_lst += str(fig.layout.shapes)

if "shapes" in relayout_data:
text_lst += json.dumps(relayout_data["shapes"], indent=2)

return text_lst

return dash.no_update

if __name__ == "__main__":
app.run_server()

输出 enter image description here

关于python - Dash中鼠标绘制图形数据的获取方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74123745/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com