一、主流繪圖庫概覽
1. 核心工具對比
庫名稱 | 特點 | 適用場景 |
---|---|---|
Matplotlib | 基礎繪圖庫,高度可定制 | 科學繪圖、論文圖表 |
Seaborn | 基于Matplotlib,統計圖表優化 | 數據分布、關系可視化 |
Plotly | 交互式可視化,支持網頁輸出 | 儀表盤、動態數據展示 |
Pandas | 內置簡易繪圖接口 | 快速數據探索 |
2. 環境準備
pip install matplotlib seaborn plotly pandas
二、Matplotlib基礎與進階
1. 基礎繪圖模板
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# 設置中文字體
matplotlib.rcParams['font.family'] = 'SimHei' # 使用黑體字體,根據實際情況修改
# 生成數據
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)# 創建畫布
plt.figure(figsize=(8, 4), dpi=100)# 繪制曲線
plt.plot(x, y, color='#FF6B6B', # 十六進制顏色linestyle='--', linewidth=2,marker='o',markersize=5,label='sin(x)')# 添加標注
plt.title("正弦函數曲線", fontsize=14, fontfamily='SimHei') # 解決中文顯示
plt.xlabel("X軸", fontsize=12)
plt.ylabel("Y軸", fontsize=12)
plt.legend(loc='upper right') # 圖例位置# 網格與樣式
plt.grid(True, linestyle=':', alpha=0.7)
plt.tight_layout() # 自動調整布局# 顯示/保存
plt.savefig('sine_curve.png', bbox_inches='tight') # 透明背景可加參數transparent=True
plt.show()
?
2. 多子圖布局
fig, axes = plt.subplots(2, 2, figsize=(10, 8)) # 2行2列# 第一個子圖
axes[0,0].plot(x, np.sin(x), label='正弦')
axes[0,0].set_title('正弦曲線')# 第二個子圖
axes[0,1].scatter(x, np.cos(x), c='green', marker='^')
axes[0,1].set_title('余弦散點')# 第三個子圖(直方圖)
axes[1,0].hist(np.random.randn(1000), bins=30, edgecolor='black', alpha=0.7)# 第四個子圖(填充圖)
axes[1,1].fill_between(x, np.sin(x), np.cos(x), where=(np.sin(x) > np.cos(x)), color='skyblue', alpha=0.4)plt.tight_layout()
?
三、Seaborn高效統計繪圖
1. 分布可視化
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset('tips')# 聯合分布圖
sns.jointplot(x='total_bill', y='tip', data=tips, kind='hex', # 可選 'reg'、'kde'marginal_kws={'color': '#4ECDC4'})# 分類箱線圖
plt.figure(figsize=(8,5))
sns.boxplot(x='day', y='total_bill', hue='sex', data=tips, palette='Pastel1')
plt.title('每日消費分布')
?
?
2. 熱力圖與聚類
# 相關性熱力圖
corr = tips.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm', linewidths=0.5, fmt='.2f')# 聚類圖
sns.clustermap(corr, cmap='viridis', figsize=(6,6), method='ward')
?
import plotly.express as px# 散點圖矩陣
fig = px.scatter_matrix(iris, dimensions=["sepal_length", "sepal_width", "petal_length", "petal_width"],color="species")
fig.show()# 3D曲面圖
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))fig = px.surface(x=x, y=y, z=Z, color_continuous_scale='Viridis')
fig.update_layout(title='3D曲面圖')
fig.show()
?
四、Plotly交互式可視化
import plotly.graph_objects as go
import numpy as np# 生成3D數據
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))fig = go.Figure(data=[go.Surface(z=Z,colorscale='Viridis',contours={ # 添加等高線"z": {"show": True, "usecolormap": True}})
])# 添加控件按鈕
fig.update_layout(title='3D動態曲面圖',scene=dict(xaxis_title='X軸',yaxis_title='Y軸',zaxis_title='Z值',camera=dict( # 預設視角eye=dict(x=1.5, y=1.5, z=0.1))),updatemenus=[ # 添加視角切換按鈕dict(type="buttons",buttons=[dict(label="俯視",method="relayout",args=[{"scene.camera.eye": {"x": 0, "y": 0, "z": 2.5}}]),dict(label="側視",method="relayout",args=[{"scene.camera.eye": {"x": 2, "y": 2, "z": 0.1}}])],direction="left",pad={"r": 10, "t": 10},showactive=True,x=0.1,xanchor="left",y=1.1,yanchor="top")]
)fig.show()