# Python中繪圖庫Matplotlib怎么用
Matplotlib是Python中最流行的2D繪圖庫,廣泛應用于數據可視化、科學計算和機器學習等領域。本文將詳細介紹Matplotlib的安裝、基礎用法、常見圖表繪制以及高級定制技巧。
## 目錄
1. [Matplotlib簡介](#matplotlib簡介)
2. [安裝與配置](#安裝與配置)
3. [基礎繪圖](#基礎繪圖)
4. [常見圖表類型](#常見圖表類型)
5. [多圖與子圖](#多圖與子圖)
6. [樣式與美化](#樣式與美化)
7. [高級功能](#高級功能)
8. [實際應用案例](#實際應用案例)
9. [常見問題解答](#常見問題解答)
---
## Matplotlib簡介
Matplotlib由John D. Hunter于2003年創建,現已成為Python數據可視化的標準庫。主要特點包括:
- 支持多種輸出格式(PNG, PDF, SVG等)
- 高度可定制的圖形元素
- 與NumPy、Pandas無縫集成
- 提供面向對象和MATLAB風格兩種API
```python
import matplotlib.pyplot as plt
import numpy as np
pip install matplotlib
import matplotlib.pyplot as plt
plt.style.use('seaborn') # 使用seaborn風格
%matplotlib inline # Jupyter Notebook魔法命令
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='sin(x)', color='blue', linestyle='--')
plt.title("Sine Wave")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.grid(True)
plt.show()
figure
: 畫布容器axes
: 實際繪圖區域axis
: 坐標軸title/label
: 標題和標簽legend
: 圖例x = np.random.randn(100)
y = x + np.random.randn(100)*0.5
plt.scatter(x, y, alpha=0.6, c='green', marker='o')
plt.title("Scatter Plot")
labels = ['A', 'B', 'C']
values = [15, 30, 45]
plt.bar(labels, values, color=['red', 'green', 'blue'])
data = np.random.randn(1000)
plt.hist(data, bins=30, edgecolor='black')
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=['A', 'B', 'C', 'D'], autopct='%1.1f%%')
plt.subplot(2, 1, 1) # 2行1列第1個
plt.plot(x, y)
plt.subplot(2, 1, 2)
plt.scatter(x, y)
fig, axes = plt.subplots(2, 2, figsize=(10, 6))
axes[0,0].plot(x, y)
axes[0,1].bar(labels, values)
plt.plot(x, y,
color='#FF5733', # HEX顏色
linestyle=':',
linewidth=2,
marker='o',
markersize=5)
print(plt.style.available) # 查看可用樣式
plt.style.use('ggplot')
plt.rcParams.update({
'font.size': 12,
'axes.titlesize': 16,
'axes.labelsize': 14
})
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
ax.scatter(x, y, z)
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
line, = ax.plot([], [])
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return line,
def update(frame):
line.set_data(x[:frame], y[:frame])
return line,
ani = FuncAnimation(fig, update, frames=len(x), init_func=init, blit=True)
import pandas as pd
data = pd.read_csv('stock.csv', parse_dates=['Date'])
plt.figure(figsize=(12, 6))
plt.plot(data['Date'], data['Close'], label='Close Price')
plt.fill_between(data['Date'], data['Low'], data['High'], alpha=0.2)
from sklearn.datasets import make_classification
X, y = make_classification(n_features=2, n_classes=3)
plt.scatter(X[:,0], X[:,1], c=y, cmap='viridis')
plt.colorbar()
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] # Mac
plt.savefig('output.png', dpi=300, bbox_inches='tight')
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1))
Matplotlib提供了強大的數據可視化能力,本文涵蓋了: - 基礎繪圖流程 - 10+種常見圖表 - 樣式美化技巧 - 高級功能應用 - 實際場景案例
通過不斷實踐,你將能夠創建出專業級的可視化作品!
提示:建議結合官方文檔(https://matplotlib.org/)深入學習更多高級功能 “`
(注:實際文章需要補充更多細節說明和示例代碼,此處為精簡版框架,完整5300字版本會擴展每個章節的詳細說明、更多示例和注意事項)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。