跳轉至

建立 2026-10-13 更新 2026-10-13

樣式與客製化

Plotly Express 的預設樣式已經可以直接使用,但正式報告通常還要調整標題、中文標籤、配色、圖例位置、懸停資訊與字型。調整分兩個層次:能在 px 函式參數完成的(labels、title、template、color_*)先用參數;參數做不到的,再用 Figure 的 update_layout、update_traces、update_xaxes/update_yaxes 方法修改。

上圖的完整程式碼:

import plotly.express as px

df = px.data.gapminder().query("year == 2007")
fig = px.scatter(
    df, x="gdpPercap", y="lifeExp", color="continent", size="pop",
    hover_name="country", log_x=True, size_max=50,
    labels={"gdpPercap": "人均 GDP(美元,對數刻度)",
            "lifeExp": "平均壽命(歲)", "continent": "洲別"},
    template="simple_white",
    title="客製化後:中文標籤、simple_white 模板",
)
fig.update_traces(marker=dict(line=dict(width=0.5, color="DarkSlateGrey")))
fig.update_layout(legend=dict(orientation="h", y=-0.2), title_x=0.5)
fig.show()

模板 template

模板(template)一次設定整張圖的字型、背景、格線與預設配色。

模板 風格
plotly 預設:淺藍灰背景、白色格線
plotly_white 白底、淺灰格線,最常用於報告
plotly_dark 深色背景,適合深色簡報或儀表板
simple_white 白底、無格線、有軸線,接近期刊論文風格
ggplot2、seaborn 模仿 R ggplot2 與 Python Seaborn
presentation 字型與線條加大,適合投影
none 無任何樣式
import plotly.io as pio

pio.templates.default = "plotly_white"   # 全域預設(對 px 與 go 都有效)
px.defaults.template = "plotly_white"    # 只對 px 有效

配色

離散色(類別)

import plotly.express as px

px.colors.qualitative.swatches().show()   # 預覽所有內建離散色盤

px.bar(df, x="continent", y="pop", color="continent",
       color_discrete_sequence=px.colors.qualitative.Set2)

px.bar(df, x="continent", y="pop", color="continent",
       color_discrete_map={"Asia": "#E45756", "Europe": "#4C78A8",
                           "Africa": "#F58518", "Americas": "#54A24B",
                           "Oceania": "#B279A2"})

color_discrete_map 讓同一個類別在不同圖中永遠是同一個顏色,製作系列報表時特別重要。顏色可以是 CSS 色名、#RRGGBB、rgb(...)。

連續色(數值)

px.colors.sequential.swatches_continuous().show()   # 預覽連續色階

px.choropleth(df, locations="iso_alpha", color="lifeExp",
              color_continuous_scale="Viridis")      # 單向色階

px.imshow(corr, color_continuous_scale="RdBu_r",
          color_continuous_midpoint=0)               # 發散色階,0 在中間

色階分三類:

  • sequential(單向):由淺到深,適合「越大越多」,例如 Viridis、Blues、Plasma。
  • diverging(發散):中點兩側不同色,適合有正負的資料,例如 RdBu、Tealrose。
  • cyclical(循環):頭尾同色,適合角度、時刻,例如 Twilight、IceFire。

色階名稱後加 _r 代表反轉,例如 "RdBu_r"。

update_layout:版面設定

fig.update_layout(
    title=dict(text="主標題", x=0.5, font=dict(size=22)),      # 置中標題
    font=dict(family="Noto Sans TC, Microsoft JhengHei, sans-serif", size=14),
    legend=dict(title="", orientation="h", yanchor="bottom", y=1.02, x=0),
    margin=dict(l=40, r=20, t=80, b=40),
    hovermode="x unified",          # 同一個 x 的所有數值顯示在一個懸停框
    width=800, height=500,
)

Plotly 的屬性可以用「底線魔法」(magic underscore)簡寫:title_x=0.5 等於 title=dict(x=0.5),legend_orientation="h" 等於 legend=dict(orientation="h")。

中文字型

圖表在瀏覽器中顯示時,使用的是瀏覽器字型,中文通常正常;但用 write_image 輸出 PNG 時若出現方框,請在 font.family 指定系統已安裝的中文字型,例如 macOS 的 "PingFang TC"、Windows 的 "Microsoft JhengHei"、Linux 的 "Noto Sans CJK TC"。

update_traces:圖形元素

fig.update_traces(marker=dict(size=10, opacity=0.8, line=dict(width=1, color="white")))
fig.update_traces(line=dict(width=3), selector=dict(name="AAPL"))  # 只改名為 AAPL 的 trace
fig.update_traces(texttemplate="%{y:.1f}", textposition="outside",
                  selector=dict(type="bar"))                       # 只改長條:數值標籤放外側

selector 參數用來篩選要修改的 trace,例如 selector=dict(type="bar") 或 selector=dict(name="Asia")。

update_xaxes/update_yaxes:座標軸

fig.update_xaxes(title_text="日期", tickformat="%Y-%m", dtick="M3")   # 每 3 個月一個刻度
fig.update_yaxes(title_text="營收(萬元)", tickformat=",", range=[0, 500],
                 showgrid=True, gridcolor="lightgrey")
fig.update_yaxes(tickprefix="$", ticksuffix="")
fig.update_xaxes(categoryorder="total descending")   # 類別依總和排序

懸停資訊 hovertemplate

hover_data 不夠用時,用 hovertemplate 完全自訂懸停框內容:

fig = px.scatter(df, x="gdpPercap", y="lifeExp", hover_name="country",
                 custom_data=["pop", "continent"])
fig.update_traces(hovertemplate=(
    "<b>%{hovertext}</b><br>"
    "人均 GDP:$%{x:,.0f}<br>"
    "平均壽命:%{y:.1f} 歲<br>"
    "人口:%{customdata[0]:,}<br>"
    "洲別:%{customdata[1]}"
    "<extra></extra>"          # 隱藏右側的 trace 名稱
))

%{x}、%{y} 取座標,%{customdata[i]} 取 custom_data 傳入的第 i 個欄位,冒號後面是 d3 數字格式。

參考線、區間與標註

fig.add_hline(y=70, line_dash="dash", line_color="red", annotation_text="70 歲")
fig.add_vrect(x0=1000, x1=5000, fillcolor="green", opacity=0.1, line_width=0,
              annotation_text="中所得", annotation_position="top left")
fig.add_annotation(x=4.5, y=82, text="日本", showarrow=True, arrowhead=2,
                   xref="x", yref="y")

注意:座標軸是對數刻度(log_x=True)時,add_annotation 的 x 要填 log10 後的值(例如 4.5 代表約 31,600)。

常用調整速查

想做的事 寫法
標題置中 fig.update_layout(title_x=0.5)
隱藏圖例 fig.update_layout(showlegend=False)
圖例放到下方 fig.update_layout(legend=dict(orientation="h", y=-0.2))
去掉圖例標題 fig.update_layout(legend_title_text="")
Y 軸顯示百分比 fig.update_yaxes(tickformat=".0%")
數字加千分位 fig.update_yaxes(tickformat=",")
背景透明 fig.update_layout(paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)")
隱藏工具列 fig.show(config={"displayModeBar": False})
長條數值標籤 px.bar(..., text_auto=True)

推薦影音

6 Quick Fixes to Improve Your Plotly Express Charts(Sven Bosau)

簡述:不到 4 分鐘示範 6 個讓 Plotly Express 預設圖表變好看的小技巧,例如換模板、改標籤、調整圖例與懸停資訊,原始碼放在 GitHub。對應本頁「常用調整速查」。

相關頁面