为关键统计表设置样式
财务部门负责人非常喜欢您之前为他们制作的关键统计表。不过,作为 Excel 的重度用户,他希望在表格上再做一些格式调整。
具体要求如下:
- 所有单元格内容左对齐。
- 单元格背景为黑色,文字为白色。
本练习是课程的一部分
使用 Dash 和 Plotly 构建仪表板
练习说明
- 在第 23 行下方,使用
defaultColDef中的cellStyle参数为所有单元格应用样式。 - 在第 25 行下方,使用
textAlign属性将单元格设置为左对齐。 - 在第 27 行下方,使用
backgroundColor和color属性将单元格设置为黑色背景、白色文字。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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)