自訂顏色

Python 的 Plotly 資料視覺化入門

Alex Scriven

Data Scientist

整體自訂方式

 

如何自訂圖表:

  1. 建立圖表時,若有參數(如 color
  2. 圖表建立後用 update_layout()
    • 接受字典
    • fig.update_layout({"title":{"text":"A New Title"}})
Python 的 Plotly 資料視覺化入門

為何要自訂顏色?

 

自訂顏色可以:

  1. 讓圖更吸睛!
  2. 傳達分析洞見
    • 此散佈圖用顏色呈現第 3 維。

   

以物種區分的顏色

Python 的 Plotly 資料視覺化入門

一些色彩理論

 

電腦用 RGB 編碼指定顏色:

  • RGB=3 位數代碼(各為 0–255),混合 Red、Green、Blue
    • (0,0,255) 是藍色,(255,255,0) 是黃色

$$

$$

詳見這篇[文章](https://en.wikipedia.org/wiki/Web_colors)

RGB 顏色範例表

Python 的 Plotly 資料視覺化入門

在 plotly.express 指定顏色

 

  • color 參數(DataFrame 欄位)
    • 類別欄位會自動配色
    • 數值欄位會使用顏色刻度

 

fig = px.bar(data_frame=student_scores, 
      x="student_name", 
      y="score", 
      title="Student Scores by Student"
      color="city")
fig.show()
Python 的 Plotly 資料視覺化入門

配色呈現結果

之前的圖:

無顏色的長條圖

加色後的圖:

有顏色的長條圖

Python 的 Plotly 資料視覺化入門

單變量圖的配色

 

在單變量(長條圖、直方圖)中使用 plotly.expresscolor 參數:

  • 直方圖:堆疊長條
  • 盒鬚圖:產生多個並列圖

帶顏色的堆疊直方圖

帶顏色的並列盒鬚圖

Python 的 Plotly 資料視覺化入門

在 plotly.express 指定特定顏色

 

  • color_discrete_map:將類別值對應到顏色的字典
  • 基本顏色也可用字串表示,如 "red""green"
Python 的 Plotly 資料視覺化入門

我們的特定配色

$$

fig = px.bar(
    data_frame=student_scores, 
    x="student_name", y="score", 
    title="Student Scores by Student",

color_discrete_map={ "Melbourne": "rgb(0,0,128)", "Sydney": "rgb(235, 207, 52)"},
color="city")

 

指定顏色的長條圖

Python 的 Plotly 資料視覺化入門

plotly.express 的色階

 

  • 單一色階(淺到深綠)

綠色色階

  • 漸層混合(綠到藍)

$$

  • 使用 color_continuous_scale 參數設定色階。

綠藍色階

Python 的 Plotly 資料視覺化入門

使用內建色階

 

fig = px.bar(data_frame=weekly_temps, 
    x="day", y="temp", 
    color="temp",
    color_continuous_scale="inferno")
fig.show()

 

$$

 

使用 inferno 色階的長條圖

Python 的 Plotly 資料視覺化入門

打造自己的色域

 

  • 自訂色階(黃-橘-紅)
my_scale=[("rgb(242, 238, 10)"),
          ("rgb(242, 95, 10)"), 
          ("rgb(255,0,0)")]

fig = px.bar(data_frame=weekly_temps, x="day", y="temp",
color_continuous_scale=my_scale, color="temp")

 

使用自訂色階的長條圖

Python 的 Plotly 資料視覺化入門

一起來練習吧!

Python 的 Plotly 資料視覺化入門

Preparing Video For Download...