我需要能够在图形中添加和删除文本注释,并通过用鼠标拖动它们来放置它们。
我正在使用 python 并且我熟悉图像注释选项,但我不知道我将如何制作动态文本注释
Plotly 非常有可能使用可拖动的注释。但是你必须释放 Dash,并将你的 plotly graph object 放在 dcc.Graph 组件中,具有以下
config
设置:
config={
'editable': True,
'edits': {
'annotationPosition': True
}
"dynamic"
,我的理解是您希望可以插入任意数量的注释。在回调中使用 dcc.Input
组件和 html.Button
非常简单。以下应用程序是由下面的完整代码片段生成的。如果这是您可以使用的东西,我很乐意更多地研究关于如何清除注释的用户友好性。现在,如果注释的输入字段为空,初始图形 fig1
将返回到 dcc.Graph
组件,没有任何注释。
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objs as go
import dash_bootstrap_components as dbc
from dash import Dash, html, dcc, Input, Output, State, dash_table, ctx
# some random data
np.random.seed(42)
y = np.random.normal(0, 10, 50)
x = np.arange(0, 50)
app = Dash(external_stylesheets=[dbc.themes.SLATE])
# initial figure for the dcc.Graph component
fig1 = px.scatter(x=x, y=y)
# app layout
app.layout = dbc.Container([dbc.Row([dbc.Col([html.H1("Dynamic and draggable annotations",
style={"text-align": "center"}, ),
dbc.Label(
'Annotation input field : '),
dcc.Input(
id='input_annotations', type='text', style={'width': '60%'}),
html.Button(id='btn_submit', type='submit', children='Add annotation')])]),
dbc.Row([dbc.Col([dcc.Graph(
id='graph1',
figure=fig1,
config={
'editable': True,
'edits': {
'shapePosition': True,
'annotationPosition': True
}
}
)])])])
# app interactivity
@app.callback(
Output(component_id='graph1', component_property='figure'),
Input(component_id='graph1', component_property='figure'),
State(component_id='input_annotations', component_property='value'),
Input('btn_submit', 'n_clicks')
)
def update_output_div(figure, annotations, n_clicks):
# Get existing figure in dcc.Graph with id='graph1'
# This lets you grap an existing figure with existing annotations
# and add more annotations to it
fig = go.Figure(figure)
# if the input field is empty,
# an initial figure is returned to id='graph1'
try:
print('trey')
if len(annotations) != 0:
fig.add_annotation(x=25, y=0,
text=annotations,
showarrow=True,
arrowcolor="black",
arrowsize=3,
arrowwidth=1,
arrowhead=1)
else:
return fig1
except:
return fig1
return fig
if __name__ == '__main__':
app.run_server(debug=True, port='8091')