简体   繁体   English

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

[英]Access plotly figure relayout data in notebook

Is there a way to access a figure relayout data in jupyter notebook/lab?有没有办法在 jupyter notebook/lab 中访问图形重新布局数据?

What I mean is the following:我的意思是:

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

I know this is possible using dash callbacks as in here .我知道使用破折号回调是可能的,就像这里一样。

You can do this fairly easily if you're willing to use Plotly Dash in Jupyterlab with JupyterDash and the mode attribute of app.run_server() set to 'inline' .如果您愿意在 JupyterDash 中使用Plotly Dash并且将app.run_server()mode属性设置为'inline' ,则可以相当容易地做到这一点。

Below is an image of the resuting notebook with full information of a drawn line in the second cell.下面是一个笔记本的图像,其中包含第二个单元格中绘制的线条的完整信息。 The complete setup with your figure is included below, and builds on one of the many examples from Image annotations with Dash .下面包含您的图形的完整设置,并建立在Image annotations with Dash的众多示例之一之上。

If this is something you can use, I'd be happy to explain things more in detail.如果这是您可以使用的东西,我很乐意更详细地解释事情。

在此处输入图像描述

Complete code:完整代码:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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