分面與動畫
分面(faceting,又稱小倍數圖 small multiples)是依某個類別欄位把一張圖拆成多張座標軸一致的小圖;動畫則是依某個欄位(通常是年份)逐格播放。兩者在 Plotly Express 中都只是一個參數:facet_row/facet_col 與 animation_frame,而且幾乎所有二維圖表函式都支援。
分面:facet_col 與 facet_row
import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker",
facet_col="day", facet_row="time",
category_orders={"day": ["Thur", "Fri", "Sat", "Sun"]})
fig.show()
所有小圖預設共用座標軸範圍,所以可以直接比較高低。常用相關設定:
| 參數或方法 | 說明 |
|---|---|
facet_col_wrap=3 |
每列最多 3 張,超過自動換行(只能搭配 facet_col,不能同時用 facet_row) |
facet_col_spacing、facet_row_spacing |
小圖之間的間距(0~1 的比例) |
fig.update_yaxes(matches=None) |
取消 Y 軸共用,每張小圖各自縮放 |
fig.for_each_annotation(...) |
修改小圖標題文字 |
小圖標題預設是 day=Sun 這種格式,去掉「欄位名=」:
分面 vs. 顏色
類別只有 2~4 個時,用 color 畫在同一張圖上方便比較;類別多、線條或點彼此重疊嚴重時,改用分面拆開。兩者也可以並用,例如 color="sex", facet_col="day"。
動畫:animation_frame 與 animation_group
import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", size="pop", color="continent",
hover_name="country",
animation_frame="year", # 每個年份一格
animation_group="country", # 同一國家在格與格之間平滑移動
log_x=True, size_max=55,
range_x=[100, 100000], range_y=[25, 90])
fig.show()
按左下角的播放鍵開始,或拖曳滑桿跳到特定年份。這就是 Hans Rosling 著名 TED 演講中的 Gapminder 動畫,在 Plotly Express 中只要一個函式呼叫。
使用動畫的注意事項:
- 固定座標軸範圍:一定要設定
range_x、range_y(地圖則是固定range_color),否則每一格的座標軸會自動縮放,動畫會跳動、無法比較。 animation_group:告訴 Plotly 哪些點是「同一個物體」,才會平滑移動而不是閃爍重畫。-
速度調整:
-
支援的函式:
scatter、line、bar、histogram、choropleth、scatter_geo、scatter_map、density_heatmap、imshow等都有animation_frame。 - 動畫適合簡報與探索,但在書面報告中,同樣的資料用分面或折線圖通常更容易精確比較。
推薦影音
Animated Scatter Plot - Python Plotly(Charming Data)
簡述:用真實資料(各國兒童預期受教年數,依性別區分)一步步做出動畫散佈圖,說明 animation_frame、animation_group 與固定座標軸範圍的重要性。對應本頁「動畫」一節。
相關頁面
- 官方範例:Facet and Trellis Plots、Animations
- 下一步:地圖