可复用的 Dash 组件

使用 Dash 和 Plotly 构建仪表板

Alex Scriven

Data Scientist

DRY 代码

 

  • DRY = Don't Repeat Yourself(也称重构)
    • 移除重复代码
  • 为重复任务编写函数
使用 Dash 和 Plotly 构建仪表板

DRY 代码示例

$$

sales_country = ecom_sales\
   .groupby('Country')['OrderValue']\
   .sum()\
   .reset_index(name='Total Sales ($)')\
   .sort_values('Total Sales ($)', 
                ascending=False)

sales_ma_cat = ecom_sales\ .groupby('Major Category')['OrderValue']\ .sum()\ .reset_index(name='Total Sales ($)')\ .sort_values('Total Sales ($)', ascending=False)

重构后:

def sales_by(col):
    df = ecom_sales\
    .groupby(col)['OrderValue']\
    .sum()\
    .reset_index(name='Total Sales ($)')\
    .sort_values('Total Sales ($)', 
                 ascending=False)
    return df

# 多次调用 sales_country = sales_by('Country') sales_ma_cat = sales_by('Major Category') sales_mi_cat = sales_by('Minor Category')
使用 Dash 和 Plotly 构建仪表板

Dash 中的 DRY

 

  • 在 Dash 中:用函数重构代码
  • 使用场景(用函数):
    • 复用 HTML(或任意)组件
    • 添加一致的样式(CSS 往往繁琐)
    • 更新样式
使用 Dash 和 Plotly 构建仪表板

复用组件

示例:样式繁多的徽标

def create_logo():
  logo=html.Img(src=logo_link, style=
  {'margin':'30px 0px 0px 0px',
  'padding':'50px 50px',
  'border':'3px dotted lightblue',
  'background-color':'rgb(230,131,247)'
  })
  return logo

 

app.layout = [
  create_logo(),
  html.Div(),
  # More components
  create_logo(),
  dcc.Graph(id='my_graph'),
  create_logo()
]

徽标被插入了 3 次!

使用 Dash 和 Plotly 构建仪表板

生成组件列表

之前:

app.layout = [
  html.Img(src=logo_link),
  html.Br(),
  html.Br(),
  html.H1("Sales breakdowns"),
  html.Br(),
  html.Br(),
  html.Br(),
  ...

之后:

def make_break(num_breaks):
    br_list = [html.Br()] * num_breaks
    return br_list

app.layout = [ html.Img(src=logo_link), *make_break(2), html.H1("Sales breakdowns"), *make_break(3), ...
使用 Dash 和 Plotly 构建仪表板

复用样式

 

  • 共享部分样式
  • 使用 Python 字典 .update()(注意:键需唯一)
d1 = {'Country':'Australia'}
d2 = {'City':'Sydney'}
d1.update(d2)
print(d1)
{'Country':'Australia', 'City':'Sydney'}
使用 Dash 和 Plotly 构建仪表板

Dash 中的样式函数

 

设置函数:

def style_c():
  corp_style={
    'margin':'0 auto',
    'border':'2px solid black',
    'display':'inline-block',
  }
  return corp_style

 

在 Dash 布局中调用:

app.layout = [
 html.Img(src=logo_link, 
 style=style_c()),

dcc.DatePickerSingle( style={'width':'200px'}.update(style_c()) )]
使用 Dash 和 Plotly 构建仪表板

Passons à la pratique !

使用 Dash 和 Plotly 构建仪表板

Preparing Video For Download...