開始使用免費開始

設定關鍵統計表格的樣式

財務部門主管非常喜歡你先前為他們製作的關鍵統計表格。不過,他是 Excel 的重度使用者,要求在表格上再做一些格式調整。

具體要求如下:

  • 所有儲存格內容都要靠左對齊。
  • 儲存格的背景要為黑色,文字為白色。

本練習屬於課程

使用 Dash 與 Plotly 建立儀表板

檢視課程

練習說明

  • 在第 23 行下方,使用 defaultColDef 中的 cellStyle 參數,將樣式套用到所有儲存格。
  • 在第 25 行下方,使用 textAlign 屬性,將儲存格設為靠左對齊。
  • 在第 27 行下方,使用 backgroundColorcolor 屬性,將儲存格設為黑底白字。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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 ($)'})

money_fmt = {"function": ("params.value.toLocaleString('en-US', {style: 'currency', currency: 'USD'})")}
column_defs = [
  {"field": "Country"},
  {"field": "Major Category"},
  {"field": "Minor Category"},
  {"field": "Total Sales ($)", "valueFormatter": money_fmt},
  {"field": "Average Order Value ($)", "valueFormatter": money_fmt},
  {"field": "Sales Volume"},
]

grid = AgGrid(
  columnDefs=column_defs,
  rowData=key_stats_tb.to_dict("records"),
  defaultColDef={
    # Apply styling to all cells
    "____": {
      # Style content aligned left
      "____": "____",
      # Style background color and text color
      "____": "____",
      "____": "____"}}
)

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)
編輯並執行程式碼