滑桿

Python 的 Plotly 資料視覺化入門

Alex Scriven

Data Scientist

什麼是滑桿?

 

  • 可在數值間切換並更新圖表的互動元件

  • 常用於隨時間瀏覽資料

  • 也可用於任何分組

$$

$$

$$

  • 💡 確保在你的圖表中有意義

 

年份滑桿:

年份滑桿

企鵝島嶼滑桿:

企鵝島嶼滑桿

Python 的 Plotly 資料視覺化入門

plotly.express 中的滑桿

 

  • animation_frame:滑桿上要顯示的欄位(前一張投影片中的「Year」或「Island」)

$$

  • animation_group:識別各影格間保持一致的樣本
Python 的 Plotly 資料視覺化入門

營收 vs. 員工數(含滑桿)

fig = px.scatter(
  data_frame=revenues, 
  y='Revenue',
  x='Employees',
  color='Industry',

animation_frame='Year', animation_group='Company')
fig.update_layout({ 'yaxis': {'range': [0, 500000]}, 'xaxis': {'range': [-100000, 2500000]} })
fig['layout'].pop('updatemenus') fig.show()

 

各年份營收

Python 的 Plotly 資料視覺化入門

限制:animate 方法

plotly.express 使用 animate 方法實作滑桿

$$

fig['layout']['sliders'][0].steps[0]['method']
animate

$$

  • 只能隨時間為「同一筆資料點」做動畫
  • 使用 traces 來建立滑桿
Python 的 Plotly 資料視覺化入門

我們的計畫

 

  1. 建立含必要 traces 的圖形物件
  2. 定義滑桿物件以顯示/隱藏 traces
  3. 更新版面配置,將滑桿加入圖形
Python 的 Plotly 資料視覺化入門

建立圖形

 

fig = go.Figure()

for island in ['Torgersen', 'Biscoe', 'Dream']: df = penguins[penguins.Island == island]
temp_trace = px.scatter(df, x="Culmen Length (mm)", y="Culmen Depth (mm)") fig.add_trace(temp_trace.data[0])
Python 的 Plotly 資料視覺化入門

建立滑桿

sliders = [
  {'steps':[

{'method': 'update', 'label': 'Torgersen',
'args': [{'visible': [True, False, False]}]},
{'method': 'update', 'label': 'Bisco',
'args': [{'visible': [False, True, False]}]},
{'method': 'update', 'label': 'Dream',
'args': [{'visible': [False, False, True]}]}
]} ]

$$

更多格式選項請見文件

Python 的 Plotly 資料視覺化入門

加入滑桿

 

$$

fig.update_layout({'sliders': sliders})
fig.show()

企鵝島嶼滑桿最終版

Python 的 Plotly 資料視覺化入門

一起來練習吧!

Python 的 Plotly 資料視覺化入門

Preparing Video For Download...