Pythonでdashを用いてダッシュボードを作成し確認する

スポンサーリンク

Pythonでdashを用いてダッシュボードを作成し確認してみます。

今回はdashを用います。このライブラリ・モジュールは、Pythonの標準ライブラリではありませんので、事前にインストールする必要があります。

■Python

今回のPythonのバージョンは、「3.8.5」を使用しています。(Windows10)(pythonランチャーでの確認)

■dashを用いてダッシュボードを作成し確認する

では、dashを用いてダッシュボードを作成してみます。

■コード

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div(children=[
    html.H1(children='テスト'),
    html.Div(children='''Dashフレームワーク'''),
    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x':[1,2,3],'y':[4,1,2],'type':'bar','name':'大阪'},
                {'x':[1,2,3],'y':[2,4,7],'type':'bar','name':'京都'},
            ],
            'layout':{
                'title':'データ解析'
            }
        }
    )
])   

if __name__ =='__main__':
    app.run_server(debug=True)

app変数を定義し、その中でdashのDashクラスを呼び出してDashを初期化。

初期化後、layoutでアプリケーションのレイアウトを作成します。dash_html_componentsのDivクラスを使用して、HTMLDivを作成します。次に、HTMLコンポーネントを使用しH1などのHTMLコンポーネントを生成します。さらに、今回は、レイアウト上にグラフを作成するために、GraphのGraphクラスを使用し、またplotly.jsを使用しデータの視覚化をレンダリング。

最後に、ダッシュボードを表示するには、Flaskと同じようにWebサーバーを実行する必要があるので、「if __name__ ==’__main__’:」とapp.run_server()を用います。括弧内には引数,パラメータとして、デバッグをtrueに設定して、変更を加えるたびにサーバーを更新し続ける必要がないようにしておきます。

■実行・検証

このスクリプトを「d_app.py」という名前で、Pythonが実行されている作業ディレクトリ(カレントディレクトリ)に保存し、コマンドプロンプトから実行してみます。

d_app.py:2: UserWarning:
The dash_core_components package is deprecated. Please replace
`import dash_core_components as dcc` with `from dash import dcc`
import dash_core_components as dcc
d_app.py:3: UserWarning:
The dash_html_components package is deprecated. Please replace
`import dash_html_components as html` with `from dash import html`
import dash_html_components as html
Dash is running on http://127.0.0.1:8050/

* Serving Flask app ‘d_app’ (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
C:\Users\user_\d_app.py:2: UserWarning:
The dash_core_components package is deprecated. Please replace
`import dash_core_components as dcc` with `from dash import dcc`
import dash_core_components as dcc
C:\Users\user_\d_app.py:3: UserWarning:
The dash_html_components package is deprecated. Please replace
`import dash_html_components as html` with `from dash import html`
import dash_html_components as html

UserWarning(ユーザー警告)や「WARNING: This is a development server. Do not use it in a production deployment.」が赤文字で出力されており、エラーが発生したかのように思われますが、これは単なる「警告」であり、エラーではないです。

出力後、Webブラウザを起動し、アドレスバーに「http://127.0.0.1:8050/」を入力し、アクセスします。

アクセスすると、今回作成したダッシュボードが表示され、ダッシュボード上にデータが視覚化されることが確認できました。

コメント

タイトルとURLをコピーしました