Plotly:如何重写标准的 dash 应用程序以在 JupyterLab 中启动它?

Plotly: How to rewrite a standard dash app to launch it in JupyterLab?

您可以在 plotly 文档中找到一堆 Dash 示例,大多数示例以关于如何使用 Dash 构建图形的注释结尾:

What About Dash? Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash at https://dash.plot.ly/installation.

但我想改为在 JupyterLab 中启动它们。那么我必须在以下 'normal' Dash 应用程序中进行哪些更改才能使其在 JupyterLab 中 运行?

代码示例:

import plotly.graph_objects as go
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html

# data and plotly figure
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')

# Set up Dash app
app = dash.Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

# Launch Dash app
app.run_server(debug=True,
               use_reloader=False # Turn off reloader if inside Jupyter
              ) 

通过在

中指定use_reloader=False,可以使用问题中描述的设置从JupyterLab 启动任何工作的 Dash 应用程序
app.run_server(debug=True,
           use_reloader=False # Turn off reloader if inside Jupyter
          ) 

但是如果您想在 launching the app in your default browser, inline in a cell or directly in Jupyter 之间使用 JupyterLab 和 select 在其自己的选项卡中,只需按照以下简单步骤操作:

更改以下行

# 1
import dash

# 2
app = dash.Dash()

# 3
app.run_server(debug=True,
           use_reloader=False # Turn off reloader if inside Jupyter
          )  

为此:

# 1
from jupyter_dash import JupyterDash

# 2
app = JupyterDash(__name__)

# 3
app.run_server(mode='inline', port = 8070, dev_tools_ui=True,
          dev_tools_hot_reload =True, threaded=True)

这将直接在 JupyterLab 中启动 Dash inline

但您也可以选择 mode='external' 启动 Dash it 自己的选项卡:

并且您可以设置 mode='external' 在您的默认浏览器中启动它。

修改后的完整代码:'

import plotly.graph_objects as go
import plotly.express as px
# import dash 
from jupyter_dash import JupyterDash

import dash_core_components as dcc
import dash_html_components as html

# data and plotly figure
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')

# Set up Dash app
# app = dash.Dash()

app = JupyterDash(__name__)

app.layout = html.Div([
    dcc.Graph(figure=fig)
])

# Launch Dash app
# app.run_server(debug=True,
#                use_reloader=False # Turn off reloader if inside Jupyter
#               )

app.run_server(mode='inline', port = 8070, dev_tools_ui=True,
          dev_tools_hot_reload =True, threaded=True)