前言
Seaborn 是 Python 常用於統計資料視覺化的高階套件,建立於 Matplotlib 的基礎之上,能用簡短的程式碼繪製出視覺效果且資訊豐富的圖表。
安裝套件
pip install seaborn
前置準備: (選項)
在 Seaborn 中要正常顯示中文,需要指定系統中已安裝的中文標題字型名稱,否則中文會變成方塊(亂碼)。
import matplotlib.font_manager as fm system_fonts = fm.fontManager.ttflist chinese_fonts = [ f.name for f in system_fonts if any(keyword in f.name for keyword in ['TC', 'HK', 'SC', 'TC', 'Ming', 'Hei', 'Kai', 'Arial Unicode']) ] print("系統中可用的中文/中日韓字型列表:") for font in sorted(set(chinese_fonts)): print(f"- {font}")Seaborn 是 Python 中另一個強大的繪圖套件,建立於 Matplotlib 的基礎上,提供更簡單、更高級、更美觀的圖表製作,支援 Pandas 的 函式庫
常用語法與參數:
樣式: dark, white, darkgrid, whitegrid
實作
散佈圖 (Scatter Plot)
散佈圖適合呈現兩組連續變數之間的相關性。在 Seaborn 中,使用 sns.scatterplot() 即可繪製,並可搭配 hue(顏色分類)與 size(點大小)來展示多維度資料。
資料結構範例
"total_bill","tip","sex","smoker","day","time","size"
16.99,1.01,"Female","No","Sun","Dinner",2
10.34,1.66,"Male","No","Sun","Dinner",3
21.01,3.5,"Male","No","Sun","Dinner",3
23.68,3.31,"Male","No","Sun","Dinner",2
27.2,4,"Male","No","Thur","Lunch",4
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt # 設定中文字型 plt.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'Microsoft JhengHei', 'PingFang TC', 'DejaVu Sans'] plt.rcParams['axes.unicode_minus'] = False # 載入內建範例資料集 tips = sns.load_dataset("tips") # 繪製散佈圖:觀察總消費金額與小費的關係,並依性別區分顏色 sns.scatterplot( data=tips, x="total_bill", y="tip", hue="sex", style="time", #time 有 Lunch/Dinner 不同類別使用不同的點形狀 size="size" ) # plt.title("Total Bill vs Tip") plt.title("總消費金額與小費的關係") plt.xlabel("總消費金額") plt.ylabel("小費") plt.show()註:
seaborn.load_dataset() 會透過 HTTPS 到 Seaborn 的 GitHub repository 下載 tips.csv
https://github.com/mwaskom/seaborn-data/blob/master/tips.csv
顯示結果
長條圖 (bar plot)
比較不同類別的數值
# 設定視覺主題 sns.set_theme(style="whitegrid") # 繪製長條圖: 比較不同星期(day)的平均總消費金額(total_bill) plt.figure(figsize=(8, 5)) ax = sns.barplot( data=tips, x="day", y="total_bill", hue="day", palette="Blues_d", legend=False, errorbar=None ) plt.title("Average Total Bill by Day", fontsize=14) plt.xlabel("Day of the Week", fontsize=12) plt.ylabel("Average Total Bill ($)", fontsize=12) plt.show()顯示結果
折線圖(Line Plot)
最常用於呈現連續性資料(特別是時間序列)的變化趨勢。在 Seaborn 中主要透過 sns.lineplot() 來繪製。
Seaborn 內建的 dowjones 資料集記錄了道瓊工業平均指數的時間序列資料,包含 Date(日期)與 Price(指數價格)兩個欄位。適合使用折線圖(Line Plot)來呈現趨勢。
基本折線圖:
呈現單一變數隨時間或順序變化的趨勢
資料結構範例
Date,Price
1914-12-01,55.0
1915-01-01,56.55
1915-02-01,56.0
1915-03-01,58.3
dowjones = sns.load_dataset("dowjones") dowjones["Date"] = pd.to_datetime(dowjones["Date"]) # 查看資料前幾行結構 print(dowjones.head()) # 設定圖表樣式 sns.set_theme(style="darkgrid") # 繪製道瓊指數折線圖 plt.figure(figsize=(10, 5)) sns.lineplot(data=dowjones, x="Date", y="Price", color="b") plt.title("Dow Jones Industrial Average", fontsize=14) plt.xlabel("Date", fontsize=12) plt.ylabel("Price", fontsize=12) plt.show()顯示結果
多重折線圖:
類別比較 利用 hue(顏色)、style(線條樣式)或 markers(數據點標記)區分不同類別
資料結構範例
subject,timepoint,event,region,signal
s13,18,stim,parietal,-0.017551581538
s5,14,stim,parietal,-0.0808829319505
s12,18,stim,parietal,-0.0810330187333
s11,18,stim,parietal,-0.04613439017519999
s10,18,stim,parietal,-0.0379702032642
[seaborn fmri]是Seaborn 內建的一個範例數據。它包含了事件相關功能核磁共振成像(Event-related fMRI)的大腦活動觀測數據。
subject: 被測試者的編號(例如:s0, s1 到 s13)
timepoint: 時間點(觀測的時間序列,0 到 18 秒)
event: 實驗事件類型(stim 代表接受刺激,cue 代表提示線索)
region: 大腦觀測區域(frontal 前額葉,parietal 頂葉)
signal: 觀測到的血氧濃度相依訊號(BOLD Signal)變化量
fmri = sns.load_dataset("fmri") # 依 event 區分顏色,依 region 區分線型 sns.lineplot( data=fmri, x="timepoint", y="signal", hue="event", style="region", markers=True, dashes=False ) plt.title("FMRI Signal over Time") plt.show()顯示結果
參考資料
https://matplotlib.org/
https://seaborn.pydata.org/