人工智能之數據分析 Matplotlib

第六章 知識總結


(文章目錄)


前言

本文對之前的關於matplotlib的知識進行系統性總結,便於知識梳理和歸納,為後續打好基礎,或者面試使用


一、核心架構

Matplotlib 採用 三層架構

  1. Backend(後端)

    • 負責圖形渲染和輸出(如 TkAggQt5AggAgg(無界面)等)
    • 通常無需手動設置,除非在服務器環境:
      import matplotlib
      matplotlib.use('Agg')  # 必須在 import pyplot 前設置
      
  2. Artist Layer(藝術家層)

    • 所有可視元素(Figure、Axes、Line、Text 等)都是 Artist 對象
    • 面向對象 API 操作此層
  3. Scripting Layer(腳本層)— pyplot

    • 提供類似 MATLAB 的簡單接口(如 plt.plot()
    • 自動管理當前 Figure 和 Axes

建議:簡單繪圖用 pyplot,複雜/可複用圖表用 面向對象 APIfig, ax = plt.subplots()


二、兩種繪圖風格

1. Pyplot 風格(命令式)

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 2])
plt.title("Title")
plt.show()
  • 適合交互式探索(如 Jupyter Notebook)
  • 隱式操作“當前”圖形

2. 面向對象風格(推薦用於腳本/項目)

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 2])
ax.set_title("Title")
plt.show()
  • 顯式控制每個組件
  • 支持多子圖、精細定製、避免狀態混亂

三、常用圖表類型與函數

圖表類型 函數 典型用途
折線圖 ax.plot(x, y) 趨勢、時間序列
散點圖 ax.scatter(x, y, c=..., s=...) 變量關係、聚類
柱狀圖 ax.bar(categories, values) 類別比較
水平柱狀圖 ax.barh(...) 類別名較長時
餅圖 ax.pie(sizes, labels=..., autopct=...) 構成比例(≤5類)
直方圖 ax.hist(data, bins=...) 數據分佈
箱線圖 ax.boxplot(data) 分佈離散度、異常值
熱力圖 ax.imshow(matrix, cmap=...)sns.heatmap() 矩陣、相關性
填充面積圖 ax.fill_between(x, y1, y2) 區間範圍

四、關鍵定製功能

1. 標題與標籤

ax.set_title("Main Title", fontsize=14)
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")

2. 刻度與網格

ax.set_xticks([0, 1, 2])
ax.set_xticklabels(['A', 'B', 'C'])
ax.grid(True, linestyle='--', alpha=0.5)

3. 圖例

ax.plot(x, y1, label='Series 1')
ax.plot(x, y2, label='Series 2')
ax.legend(loc='upper left')

4. 顏色與樣式

  • 顏色:color='red''#FF5733'[0.1, 0.8, 0.3]
  • 線型:linestyle='--'ls=':'
  • 標記:marker='o', markersize=8

5. 多子圖

fig, axs = plt.subplots(2, 2, figsize=(10, 8))
axs[0, 0].plot(...)
plt.tight_layout()  # 自動防重疊

五、圖像處理(謹慎使用)

⚠️ plt.imread / imsave 已棄用,建議用 Pillowimageio

功能 推薦方式
讀圖 np.array(Image.open('img.jpg'))
顯示 ax.imshow(img)
保存 Image.fromarray(arr).save('out.png')

六、中文顯示解決方案

# 方法1:全局設置(Windows)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False  # 解決負號顯示

# 方法2:指定字體路徑(跨平台)
from matplotlib import font_manager
my_font = font_manager.FontProperties(fname="/path/to/simhei.ttf")
ax.set_title("標題", fontproperties=my_font)

七、與 Seaborn 協同

  • Seaborn 是 Matplotlib 的高級封裝,默認使用 Matplotlib 渲染
  • 設置 Seaborn 樣式會影響後續所有 Matplotlib 圖:
    sns.set_style("whitegrid")
    sns.set_palette("Set2")
    
  • 混合使用:
    fig, ax = plt.subplots()
    sns.boxplot(data=df, x='category', y='value', ax=ax)
    ax.set_title("Custom Title via Matplotlib")
    

八、最佳實踐

Do’s

  • 使用 figsize 控制畫布大小
  • dpi=300 + bbox_inches='tight' 保存高清圖
  • 多子圖用 plt.subplots() + tight_layout()
  • 複雜圖表優先用面向對象 API
  • 探索數據時結合 Seaborn 快速出圖

Don’ts

  • 不要寫 plt.plot(...)... 是 Ellipsis,會報錯!)
  • 避免在循環中不關閉圖形(內存泄漏)→ 用 plt.close()
  • 餅圖類別 > 5 時改用條形圖
  • 不要在服務器環境使用交互式後端(如 Tkinter)

九、常用配置速查

# 全局設置示例
plt.rcParams.update({
    'figure.figsize': (10, 6),
    'font.size': 12,
    'lines.linewidth': 2,
    'axes.grid': True,
    'axes.spines.top': False,
    'axes.spines.right': False
})

十、調試技巧

  • 查看當前後端:matplotlib.get_backend()
  • 列出可用字體:matplotlib.font_manager.findSystemFonts()
  • 清空當前圖:plt.clf();關閉窗口:plt.close()
  • Jupyter 內聯顯示:%matplotlib inline

📌 一句話總結“簡單用 pyplot,複雜用 axes;中文設字體,多圖用 subplots;高清靠 savefig,美觀靠 Seaborn。”


後續

python過渡項目部分代碼已經上傳至gitee,後續會逐步更新。

資料關注

公眾號:咚咚王 gitee:https://gitee.com/wy18585051844/ai_learning

《Python編程:從入門到實踐》 《利用Python進行數據分析》 《算法導論中文第三版》 《概率論與數理統計(第四版) (盛驟) 》 《程序員的數學》 《線性代數應該這樣學第3版》 《微積分和數學分析引論》 《(西瓜書)周志華-機器學習》 《TensorFlow機器學習實戰指南》 《Sklearn與TensorFlow機器學習實用指南》 《模式識別(第四版)》 《深度學習 deep learning》伊恩·古德費洛著 花書 《Python深度學習第二版(中文版)【純文本】 (登封大數據 (Francois Choliet)) (Z-Library)》 《深入淺出神經網絡與深度學習+(邁克爾·尼爾森(Michael+Nielsen)》 《自然語言處理綜論 第2版》 《Natural-Language-Processing-with-PyTorch》 《計算機視覺-算法與應用(中文版)》 《Learning OpenCV 4》 《AIGC:智能創作時代》杜雨+&+張孜銘 《AIGC原理與實踐:零基礎學大語言模型、擴散模型和多模態模型》 《從零構建大語言模型(中文版)》 《實戰AI大模型》 《AI 3.0》