首页 > 解决方案 > Plotly:如何重写标准仪表板应用程序以在 JupyterLab 中启动它?

问题描述

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

达世币呢?Dash 是一个用于构建分析应用程序的开源框架,不需要 Javascript,它与 Plotly 图形库紧密集成。

在https://dash.plot.ly/installation了解如何安装 Dash 。

但我想改为在 JupyterLab 中启动它们。那么我必须在以下“普通”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
              ) 

标签: pythonplotlyplotly-dashjupyter-labplotly-python

解决方案


任何工作的 Dash 应用程序都可以使用问题中描述的设置JupyterLab 启动,方法是指定use_reloader=False

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

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

更改以下行

# 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:

在此处输入图像描述

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

在此处输入图像描述

您可以设置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)

推荐阅读