互動式關鍵統計表
用圖表來呈現資料,是快速查看彙總數值的好方法。不過,有時你也需要看到比一般視覺化格式更大量的數字。
電商公司的關鍵利害關係人——財務部門主管——聽說了你的成果,但他習慣用表格而非圖表來看數字。他希望建立一個儀表板,以表格方式顯示一些彙總統計。不過,他也想知道你是否能加入一點「Dash 魔法」,讓它比他現有的 Excel 試算表更具互動性?
本練習屬於課程
使用 Dash 與 Plotly 建立儀表板
練習說明
- 在第 9 行之後,設定
money_fmt物件,用於 USD 貨幣格式化,並使用正確的函式與樣式參數。 - 在第 15 行之後,將
money_fmt格式器加入column_defs中的'Total Sales ($)'欄位。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
from dash import Dash, dcc, html, Input, Output, callback
import plotly.express as px
import pandas as pd
from dash_ag_grid import AgGrid
ecom_sales = pd.read_csv('/usr/local/share/datasets/ecom_sales.csv')
logo_link = 'https://assets.datacamp.com/production/repositories/5893/datasets/fdbe0accd2581a0c505dab4b29ebb66cf72a1803/e-comlogo.png'
key_stats_tb = ecom_sales.groupby(['Country','Major Category', 'Minor Category'])['OrderValue'].agg(['sum', 'count', 'mean']).reset_index().rename(columns={'count':'Sales Volume', 'sum':'Total Sales ($)', 'mean':'Average Order Value ($)'})
# Set up the money object
money_fmt = {
"____": (
"""params.value.toLocaleString(
'en-US', {style: '____', currency: '____'})""")}
# Add the formatter to the relevant column
column_defs = [
{"field": "Major Category"},
{"field": "Total Sales ($)", "____": ____},
{"field": "Average Order Value ($)"},
{"field": "Sales Volume"}]
grid = AgGrid(
columnDefs=column_defs,
rowData=key_stats_tb.to_dict("records"))
app = Dash()
app.layout = [
html.Img(src=logo_link, style={'margin':'30px 0px 0px 0px'}),
html.H1('Sales Aggregations'),
html.Div([
html.H2('Key Aggregations'),
grid],
style={'width':'850px', 'height':'750px', 'margin':'0 auto'})
]
if __name__ == '__main__':
app.run(debug=True)