Python 如何在Plotly的Plotly Dash应用程序中将多个图表添加到单个浏览器页面中
Plotly是Python中的一个开源绘图库,可以生成多种不同类型的图表。Python用户可以使用Plotly创建交互式的基于Web的可视化,可以在Jupyter笔记本中显示,保存为独立的HTML文件,或作为使用Dash的Web应用程序的一部分提供。Plotly还可用于静态文档发布和桌面编辑器(例如PyCharm和Spyder)。
Dash是一个Python框架,用于创建交互式的基于Web的仪表板应用程序。dash库将所有所需的库添加到基于Web的仪表板应用程序中。
在本教程中,我们将展示如何在单个浏览器页面上将多个图表添加到Plotly Dash应用程序中。按照以下步骤生成单个页面上的多个Dash应用程序。
步骤1
导入Dash库。
import dash
步骤2
导入Dash核心组件, dcc 和 html 。
from dash import dcc,html
步骤3
导入以下 Dash 依赖。
from dash.dependencies import Input, Output
步骤4
导入 plotly.express 模块并命名别名为 px 。
import plotly.express as px
步骤5
使用Pandas模块生成数据集
import pandas as pd
df_bar = pd.DataFrame({
"Season": ["Summer", "Winter", "Autumn", "Spring"],
"Rating": [3,2,1,4]
})
步骤6
使用以下数值生成一个柱状图,并将其存储在”fig”变量中。
fig = px.bar(df_bar, x="Season", y="Rating", barmode="group")
步骤7
使用以下命令创建 main 函数以运行App服务器
app = dash.Dash(__name__)
if __name__ == '__main__':
app.run_server(debug=True)
步骤8
在两个“div”区域中生成两个不同HTML子元素的应用布局。
app.layout = html.Div(children=[
# elements from the top of the page
html.Div([html.H1(children='Dash app1'),
html.Div(children='''Dash: First graph.'''),
dcc.Graph(id='graph1',figure=fig),]),
# New Div for all elements in the new 'row' of the page
html.Div([
html.H1(children='Dash app2'),
html.Div(children='''Dash: Second graph.'''),
dcc.Graph(id='graph2',figure=fig),
]),
])
示例
这是使用Dash在单个网页上创建多个图表的完整代码 –
import dash
from dash import dcc,html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
app = dash.Dash(__name__)
df_bar = pd.DataFrame({
"Season": ["Summer", "Winter", "Autumn", "Spring"],
"Rating": [3,2,1,4]
})
fig = px.bar(df_bar, x="Season", y="Rating", barmode="group")
app.layout = html.Div(children=[
# elements from the top of the page
html.Div([
html.H1(children='Dash app1'),
html.Div(children='''
Dash: First graph.'''),
dcc.Graph(
id='graph1',
figure=fig
),
]),
# New Div for all elements in the new 'row' of the page
html.Div([
html.H1(children='Dash app2'),
html.Div(children='''
Dash: Second graph. '''),
dcc.Graph(
id='graph2',
figure=fig
),
]),
])
if __name__ == '__main__':
app.run_server(debug=True)
输出
当您执行上述程序时,您将在控制台上获得以下输出 –
Dash is running on http://127.0.0.1:8050/
* Serving Flask app 'main'
* Debug mode: on
当点击URL时,您将被重定向到浏览器,该浏览器将显示以下输出−