Matplotlib 是 Python 最常用的 數據可視化 庫之一,在數據挖掘過程中,主要用于 數據探索 (EDA)、趨勢分析、模式識別 和 結果展示。
📌 1. Matplotlib 基礎
1.1 安裝 & 導入
# 如果未安裝 Matplotlib,請先安裝
# pip install matplotlibimport matplotlib.pyplot as plt
import numpy as np
1.2 基本繪圖
x = np.linspace(0, 10, 100) # 生成 100 個 0-10 之間的等距點
y = np.sin(x)plt.plot(x, y) # 畫圖
plt.xlabel("X 軸") # X 軸標簽
plt.ylabel("Y 軸") # Y 軸標簽
plt.title("Sine Wave") # 圖標題
plt.grid(True) # 添加網格
plt.show() # 顯示圖像
📌 輸出: 繪制 正弦曲線 📈
📌 2. 常見圖表類型
2.1 折線圖 (Line Plot)
x = np.arange(1, 11)
y = np.random.randint(10, 100, size=10)plt.plot(x, y, marker="o", linestyle="-", color="b", label="數據趨勢")
plt.legend()
plt.show()
📌 適用場景: 用于 趨勢分析 和 時間序列數據
2.2 散點圖 (Scatter Plot)
x = np.random.rand(50)
y = np.random.rand(50)plt.scatter(x, y, color="g", alpha=0.7) # 透明度 alpha 控制點的透明度
plt.title("Scatter Plot")
plt.show()
📌 適用場景: 適合用于 關系分析、聚類分析
2.3 柱狀圖 (Bar Chart)
categories = ["A", "B", "C", "D", "E"]
values = [10, 25, 15, 30, 20]plt.bar(categories, values, color="orange")
plt.title("Bar Chart Example")
plt.show()
📌 適用場景: 適用于 類別數據分析
2.4 直方圖 (Histogram)
data = np.random.randn(1000) # 生成 1000 個隨機數plt.hist(data, bins=30, color="purple", alpha=0.75)
plt.title("Histogram Example")
plt.show()
📌 適用場景: 適合 分布分析,如 正態分布檢驗
2.5 盒須圖 (Box Plot)
data = [np.random.rand(100) * i for i in range(1, 5)]plt.boxplot(data, patch_artist=True)
plt.title("Box Plot Example")
plt.show()
📌 適用場景: 適合 異常值分析、數據分布分析
📌 3. 進階繪圖技巧
3.1 子圖 (Subplot)
fig, axes = plt.subplots(2, 2, figsize=(10, 8))x = np.linspace(0, 10, 100)
axes[0, 0].plot(x, np.sin(x))
axes[0, 0].set_title("Sine Wave")axes[0, 1].scatter(np.random.rand(50), np.random.rand(50))
axes[0, 1].set_title("Scatter Plot")axes[1, 0].bar(["A", "B", "C"], [10, 20, 30])
axes[1, 0].set_title("Bar Chart")axes[1, 1].hist(np.random.randn(1000), bins=30)
axes[1, 1].set_title("Histogram")plt.tight_layout() # 自動調整子圖間距
plt.show()
📌 適用場景: 在 一個畫布上同時繪制多個圖表
3.2 統計相關性分析
import seaborn as sns
import pandas as pd# 生成隨機數據
df = pd.DataFrame(np.random.rand(10, 4), columns=["A", "B", "C", "D"])# 計算相關性
correlation_matrix = df.corr()# 相關性熱圖
plt.figure(figsize=(8, 6))
sns.heatmap(correlation_matrix, annot=True, cmap="coolwarm", linewidths=0.5)
plt.title("Correlation Matrix Heatmap")
plt.show()
📌 適用場景: 特征工程、變量相關性分析
3.3 動態更新數據
import timeplt.ion() # 開啟交互模式
fig, ax = plt.subplots()x = []
y = []for i in range(10):x.append(i)y.append(np.random.randint(1, 10))ax.clear()ax.plot(x, y, marker="o", linestyle="-", color="b")plt.pause(0.5)plt.ioff() # 關閉交互模式
plt.show()
📌 適用場景: 實時數據可視化,如股市走勢
📌 4. Matplotlib 在數據挖掘中的應用
數據挖掘任務 | 適用圖表 |
---|---|
數據探索 (EDA) | 直方圖、盒須圖、散點圖 |
趨勢分析 | 折線圖 |
相關性分析 | 熱圖、散點圖 |
異常值檢測 | 盒須圖 |
分類數據分析 | 柱狀圖 |
數據分布分析 | 直方圖 |
📌 5. 總結
Matplotlib 在數據挖掘中的核心作用: ? 數據可視化:幫助理解數據的分布、趨勢、相關性
? 異常值檢測:通過箱線圖、散點圖檢測異常點
? 模式識別:發現數據中的模式或聚類結構
? 結果展示:清晰直觀地展示數據分析和挖掘結果