在笔记本中访问 plotly figure 重新布局数据

Access plotly figure relayout data in notebook

有没有办法在 jupyter 中访问图形重新布局数据notebook/lab?

我的意思是:

import plotly.graph_objects as go

# Define the figure
fig = (go.Figure(
    go.Scatter(
        x=[0, 1, 2, 3],
        y=[-1, 1, -2, 2]
       )
    )
    .update_layout(
        modebar_add=['drawrect']
    )
)

# Show the figure
fig.show()
# Now do some drawing in the figure here! 

# Next cell I would like to access the shapes

我知道这可以使用 here 中的破折号回调实现。

如果您愿意使用 Plotly Dash in Jupyterlab with JupyterDash 并将 app.run_server()mode 属性设置为 'inline'

,您可以很容易地做到这一点

下面是结果笔记本的图像,其中包含第二个单元格中绘制的线条的完整信息。下面包含了您的图形的完整设置,并基于 Image annotations with Dash.

中的众多示例之一

如果这是您可以使用的东西,我很乐意更详细地解释。

完整代码:

import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_html_components as html
from jupyter_dash import JupyterDash
import plotly.express as px
import plotly.graph_objects as go
import json

app = JupyterDash(external_stylesheets=[dbc.themes.BOOTSTRAP])

fig = (go.Figure(
    go.Scatter(
        x=[0, 1, 2, 3],
        y=[-1, 1, -2, 2]
       )
    ))

fig.update_layout(dragmode="drawline")
config = {
    "modeBarButtonsToAdd": [
        "drawline",
        "drawopenpath",
        "drawclosedpath",
        "drawcircle",
        "drawrect",
        "eraseshape",
    ]
}

app.layout = html.Div(
    [
        html.H4(
            "Draw a line"
        ),
        dcc.Graph(id="graph1", figure=fig, config=config),
        # dcc.Markdown("Characteristics of shapes"),
        html.Pre(id="annotations-data-pre"),
    ]
)

@app.callback(
    Output("annotations-data-pre", "children"),
    Input("graph1", "relayoutData"),
    prevent_initial_call=True,
)
def on_new_annotation(relayout_data):
    if "shapes" in relayout_data:
        global relayoutdata
        relayoutdata = json.dumps(relayout_data["shapes"], indent=2)
        return ''
    else:
        return dash.no_update

app.run_server(mode='inline', port=8002)