如何在Python Plotly中將多個圖表新增到Plotly Dash應用程式的單個瀏覽器頁面上?
Plotly 是一個 Python 中的開源繪相簿,可以生成多種不同型別的圖表。Python 使用者可以使用 Plotly 建立互動式的基於 Web 的視覺化效果,這些視覺化效果可以顯示在 Jupyter Notebook 中,儲存到獨立的 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
為兩個不同的 HTML 子元素在兩個“div”部分中生成 App 佈局。
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 後,您將被重定向到瀏覽器,該瀏覽器將顯示以下輸出:
廣告