python - 访问笔记本中的绘图图形重新布局数据

标签 python plotly jupyter plotly-python

有没有办法访问 jupyter 笔记本/实验室中的图形重新布局数据?

我的意思是:

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,您可以相当轻松地做到这一点在 Jupyterlab 中使用 JupyterDash并且 app.run_server()mode 属性设置为 'inline'

下面是生成的笔记本的图像,其中包含第二个单元格中绘制的线条的完整信息。下面包含了您的图形的完整设置,并基于 Image annotations with Dash. 中的众多示例之一构建。

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

enter image description here

完整代码:

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)

关于python - 访问笔记本中的绘图图形重新布局数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70742352/

相关文章:

python - ImageGrid 中每一行的颜色条

javascript - Angular2 应用程序问题 - 必须执行该函数两次,才能强制显示更改

python - 如何从 Jupyter notebook 获取操作系统命令的输出?

python - 为什么 memcache 在我的 Django 中不起作用?

python - ModuleNotFoundError : No module named 'werkzeug.posixemulation'

python - 达到内存限制时退出 Python 程序

python - 如何在不使用 ipython 的情况下将 jupyter notebook 配置为具有带有某些导入的预加载单元格?

python - Plotly 静态图像导出出现 OSError : [WinError 193] %1 is not a valid Win32 application

python - 将特定线条添加到 Plotly Scatter3d() 图中

python导入一个非标准库