Plotly 图表与图形

使用 Dash 和 Plotly 构建仪表板

Alex Scriven

Data Scientist

什么是 Dash?

  • 用于创建交互式网页应用的 Python 库

$$

$$

优点:

  • 免费!不同于 Tableau 或 PowerBI
  • 仅用 Python 即可利用 JavaScript
  • 比网页应用框架代码更少
使用 Dash 和 Plotly 构建仪表板

Plotly 与 Dash

  • 协同良好

$$

  • Dash:包含多个 Plotly 图表的交互式仪表板
  • 参见此示例

 

金融仪表板示例截图,包含多种图表、文本、表格和图片,其中有带悬停细节的折线图

使用 Dash 和 Plotly 构建仪表板

什么是 Plotly?

 

  • 回顾 Plotly,重点讲解 Dash
  • 一个用于创建现代交互式图表的 Python 库
    • 封装 JavaScript,但用 Python 编码
  • 使用 plotly.express 创建图表

$$

$$

$$

使用 Dash 和 Plotly 构建仪表板

我们的电商数据

  • 电商销售数据集

$$

$$

  • 详情:
    • 商品类别(大类、小类)与描述
    • 单价、数量(+ 订单金额)
    • 国家
    • 销售年月

电商销售示意图

使用 Dash 和 Plotly 构建仪表板

使用 plotly.express 绘制折线图

 

import plotly.express as px

line_graph = px.line(
data_frame=ecom_sales, x='Year-Month', y='Total Sales ($)', title='Total Sales by Month')
line_graph.show()

 

一个按月销售额的折线图 GIF,鼠标悬停在点上以显示月份和销售额

使用 Dash 和 Plotly 构建仪表板

使用 plotly.express 绘制柱状图

$$

bar_fig = px.bar(
  data_frame=ecom_sales,
  x='Total Sales ($)',
  y='Country',
  title='Total Sales by Country',

orientation='h')
bar_fig.show()

 

一个水平柱状图的 GIF:x 轴为总销售额,y 轴为国家。鼠标悬停显示数据

使用 Dash 和 Plotly 构建仪表板

自定义 Plotly 图表

 

调整柱宽:

bar_fig.update_layout({'bargap': 0.5})

bar_fig.show()

$$

$$

$$

查看 Plotly 文档

 

一个水平柱状图:x 轴为总销售额,y 轴为国家。与上一页相同,但柱间距更小。

使用 Dash 和 Plotly 构建仪表板

Vamos praticar!

使用 Dash 和 Plotly 构建仪表板

Preparing Video For Download...