子圖(Subplots)

Python 的 Plotly 資料視覺化入門

Alex Scriven

Data Scientist

什麼是子圖?

 

  • 子圖:排列在網格中的「小型圖表」

$$

  • 可顯示不同圖表類型(同一資料)或不同資料子集

 

子圖示意

Python 的 Plotly 資料視覺化入門

關於 traces 的提醒

 

  • Plotly 圖表包含 traces 清單——資料與類型

  • fig.data[0]fig.data[1] 存取

    • 可用 .add_trace() 加到子圖

$$

px_fig = px.scatter(df...)
print(px_fig)
Figure({'data': [trace1], 'layout': {...}})
Python 的 Plotly 資料視覺化入門

建立 1x2 子圖

import plotly.express as px
from plotly.subplots import make_subplots

# Create a subplot grid
fig = make_subplots(rows=2, cols=1)

# Create plotly express figures hist = px.histogram(revenues, x='Revenue') box = px.box(revenues, x='Revenue')
# Extract traces and add to subplots fig.add_trace(hist.data[0], row=1, col=1) fig.add_trace(box.data[0], row=2, col=1) fig.show()

 

財務範例子圖

Python 的 Plotly 資料視覺化入門

自訂子圖

 

  • 沒有整體圖表標題
  • 沒有子圖標題

$$

$$

$$

  • ✨ 打造成可上台簡報的水準

 

簡單的財務子圖

Python 的 Plotly 資料視覺化入門

子圖標題

from plotly.subplots import make_subplots

fig = make_subplots(rows=2, cols=1,
    subplot_titles=[
    'Histogram of company revenues', 
    'Box plot of company revenues'])

## Add in traces (fig.add_trace())
fig.update_layout({'title': {'text': 'Plots of company revenues', 'x': 0.5, 'y': 0.9}}) fig.show()
Python 的 Plotly 資料視覺化入門

堆疊子圖

$$

fig = make_subplots(rows=3, cols=1, 
  subplot_titles=['Adelie Penguins'
  , 'Gentoo Penguins', 'Chinstrap Penguins'])

row_num = 1 for species in ['Adelie', 'Gentoo', 'Chinstrap']: # Filter data for this species df = penguins[penguins['Species'] == species]
scatter = px.scatter(df, x='Culmen Length (mm)' , y='Culmen Depth (mm)') # Add the trace to the subplot fig.add_trace(scatter.data[0] , row=row_num, col=1) row_num +=1

企鵝子圖(縱向堆疊)

Python 的 Plotly 資料視覺化入門

共用座標軸的子圖

 

  • 讓 x 軸「共用」:
fig = make_subplots(
    rows=3, cols=1
    , shared_xaxes=True)

共用 x 軸的企鵝子圖

Python 的 Plotly 資料視覺化入門

一起來練習吧!

Python 的 Plotly 資料視覺化入門

Preparing Video For Download...