Python數(shù)據(jù)可視化完全指南之Matplotlib+Seaborn+Plotly用法詳解
前言
數(shù)據(jù)本身不會說話,但好的可視化能讓數(shù)據(jù)"開口"。一個精心設(shè)計的圖表,勝過千言萬語的數(shù)據(jù)描述。
Python 生態(tài)中有三個主流的可視化庫,它們各有定位:

| 庫 | 一句話特點 | 最佳場景 |
|---|---|---|
| Matplotlib | 靈活但需要更多代碼 | 自定義圖表、學(xué)術(shù)論文 |
| Seaborn | 美觀且代碼簡潔 | 統(tǒng)計分析、EDA |
| Plotly | 交互式、Web 友好 | 儀表盤、在線報告 |
本文將通過大量實際運行的圖表,帶你全面掌握 Python 數(shù)據(jù)可視化。

第一章:Matplotlib —— Python 可視化的基石
1.1 快速入門
Matplotlib 是 Python 可視化生態(tài)的根基。幾乎所有高級可視化庫都在它之上構(gòu)建。
pip install matplotlib
import matplotlib.pyplot as plt import numpy as np # 設(shè)置中文字體(Windows) plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False
Figure 與 Axes 概念
Matplotlib 有兩個核心概念:

- Figure:整個畫布(窗口)
- Axes:畫布上的一個子圖(包含坐標軸、數(shù)據(jù)區(qū)域)
創(chuàng)建圖表有兩種風格:
# 方法1: 面向?qū)ο箫L格(推薦)
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, y)
ax.set_title('標題')
ax.set_xlabel('X軸')
plt.show()
# 方法2: pyplot 風格(簡單快捷)
plt.figure(figsize=(10, 6))
plt.plot(x, y)
plt.title('標題')
plt.show()
1.2 折線圖:展示趨勢變化
折線圖是使用最廣泛的圖表類型,特別適合展示數(shù)據(jù)隨時間的變化趨勢。
運行效果:

x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, np.sin(x), label='sin(x)', linewidth=2, color='#e74c3c')
ax.plot(x, np.cos(x), label='cos(x)', linewidth=2, color='#3498db')
ax.plot(x, np.sin(x) * np.exp(-x/5), label='sin(x)·e^(-x/5)',
linewidth=2, color='#2ecc71', linestyle='--')
ax.set_title('三角函數(shù)折線圖', fontsize=16, fontweight='bold')
ax.legend(fontsize=11)
ax.grid(True, alpha=0.3)
ax.fill_between(x, np.sin(x), alpha=0.1) # 填充區(qū)域
plt.tight_layout()
plt.savefig('折線圖.png', dpi=150)
折線圖樣式參數(shù)速查:
| 參數(shù) | 可選值 | 說明 |
|---|---|---|
linestyle | '-', '--', '-.', ':' | 線型 |
linewidth | 數(shù)值 | 線寬 |
color | 顏色名/十六進制/RGB元組 | 顏色 |
marker | 'o', 's', '^', '*', '+' | 數(shù)據(jù)點標記 |
alpha | 0~1 | 透明度 |
1.3 柱狀圖:對比分類數(shù)據(jù)
柱狀圖適合比較不同類別之間的數(shù)值差異。
運行效果:

categories = ['Python', 'JavaScript', 'Java', 'Go', 'Rust', 'TypeScript']
values_2024 = [68, 62, 48, 35, 28, 38]
values_2025 = [72, 58, 42, 45, 42, 52]
x_pos = np.arange(len(categories))
width = 0.35
fig, ax = plt.subplots(figsize=(10, 6))
bars1 = ax.bar(x_pos - width/2, values_2024, width, label='2024年', color='#3498db')
bars2 = ax.bar(x_pos + width/2, values_2025, width, label='2025年', color='#e74c3c')
# 添加數(shù)值標簽
for bar in bars1:
ax.text(bar.get_x() + bar.get_width()/2., bar.get_height() + 0.5,
f'{int(bar.get_height())}', ha='center', fontsize=10)
ax.set_title('編程語言流行度對比', fontsize=16, fontweight='bold')
ax.set_xticks(x_pos)
ax.set_xticklabels(categories)
ax.legend()
ax.grid(axis='y', alpha=0.3)
柱狀圖變體:
# 水平柱狀圖 ax.barh(y_pos, values, height=0.6) # 堆疊柱狀圖 ax.bar(categories, values1, label='A') ax.bar(categories, values2, bottom=values1, label='B') # 分組柱狀圖(上面示例) ax.bar(x - width/2, values1, width, label='A') ax.bar(x + width/2, values2, width, label='B')
1.4 散點圖:發(fā)現(xiàn)數(shù)據(jù)關(guān)聯(lián)
散點圖展示兩個變量之間的關(guān)系,是探索性數(shù)據(jù)分析(EDA)中最常用的圖表。
運行效果:

np.random.seed(42)
n = 200
fig, ax = plt.subplots(figsize=(10, 8))
# 三類數(shù)據(jù)點
ax.scatter(x1, y1, alpha=0.6, s=50, c='#e74c3c', label='A類')
ax.scatter(x2, y2, alpha=0.6, s=50, c='#3498db', label='B類')
ax.scatter(x3, y3, alpha=0.6, s=50, c='#2ecc71', label='C類')
ax.set_title('三類數(shù)據(jù)散點圖', fontsize=16, fontweight='bold')
ax.legend(fontsize=11)
ax.grid(True, alpha=0.2)
散點圖高級參數(shù):
| 參數(shù) | 說明 | 示例 |
|---|---|---|
s | 點的大小 | s=50 或 s=array_of_sizes |
c | 點的顏色 | c='red' 或 c=array_of_values |
cmap | 顏色映射 | cmap='viridis' |
alpha | 透明度 | alpha=0.6 |
edgecolors | 邊框顏色 | edgecolors='white' |
marker | 標記形狀 | marker='o', 's', '^' |
1.5 餅圖:展示占比關(guān)系
運行效果:

languages = ['Python', 'JavaScript', 'Java', 'Go', 'Rust', '其他']
shares = [30, 25, 18, 12, 8, 7]
colors = ['#3498db', '#f39c12', '#e74c3c', '#2ecc71', '#9b59b6', '#95a5a6']
explode = (0.05, 0.02, 0.02, 0.02, 0.02, 0.02) # 突出顯示某塊
fig, ax = plt.subplots(figsize=(9, 9))
wedges, texts, autotexts = ax.pie(
shares, labels=languages, colors=colors, explode=explode,
autopct='%1.1f%%', shadow=True, startangle=90
)
ax.set_title('編程語言市場份額 (2025)', fontsize=16, fontweight='bold')
建議:餅圖類別不宜超過 6 個。超過 6 個建議使用水平柱狀圖替代。
1.6 子圖布局:一圖多表
運行效果:

fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 子圖1: 正弦曲線
axes[0, 0].plot(x, np.sin(x), color='#e74c3c', linewidth=2)
axes[0, 0].set_title('sin(x)', fontsize=13)
axes[0, 0].grid(True, alpha=0.3)
# 子圖2: 余弦曲線
axes[0, 1].plot(x, np.cos(x), color='#3498db', linewidth=2)
axes[0, 1].set_title('cos(x)', fontsize=13)
# 子圖3: 直方圖
axes[1, 0].hist(data, bins=30, color='#2ecc71', edgecolor='white')
axes[1, 0].set_title('正態(tài)分布直方圖')
# 子圖4: 水平柱狀圖
axes[1, 1].barh(brands, sales, color=['#e74c3c', '#3498db', ...])
axes[1, 1].set_title('手機品牌銷量')
fig.suptitle('子圖布局示例', fontsize=18, fontweight='bold')
plt.tight_layout()
子圖布局方法對比:
| 方法 | 適用場景 | 示例 |
|---|---|---|
plt.subplots(nrows, ncols) | 規(guī)則網(wǎng)格 | subplots(2, 3) → 2行3列 |
fig.add_subplot(1,2,1) | 不規(guī)則布局 | 手動添加每個子圖 |
plt.subplot2grid((3,3), (0,0), colspan=2) | 跨行/列布局 | 精確控制每個子圖位置 |
gridspec.GridSpec | 最靈活 | 完全自定義布局 |
1.7 熱力圖:矩陣可視化
運行效果:

np.random.seed(42)
data = np.random.rand(10, 10)
fig, ax = plt.subplots(figsize=(10, 8))
im = ax.imshow(data, cmap='RdYlBu_r', aspect='auto')
# 添加數(shù)值標注
for i in range(10):
for j in range(10):
ax.text(j, i, f'{data[i, j]:.2f}', ha='center', va='center',
fontsize=8, color='black' if data[i, j] > 0.5 else 'white')
plt.colorbar(im, ax=ax, shrink=0.8, label='相關(guān)系數(shù)')
ax.set_title('特征相關(guān)性熱力圖', fontsize=16, fontweight='bold')
常用顏色映射(colormap):
| 類型 | 名稱 | 適用場景 |
|---|---|---|
| 順序型 | 'viridis', 'Blues', 'Greens' | 連續(xù)數(shù)值,從低到高 |
| 發(fā)散型 | 'RdYlBu', 'coolwarm', 'seismic' | 有中間值的正負數(shù)據(jù) |
| 分類型 | 'Set1', 'Set2', 'tab10' | 不同類別區(qū)分 |
| 灰度 | 'gray', 'Greys' | 黑白打印 |
1.8 面積圖與箱線圖
面積圖
運行效果:

months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
product_a = [30, 35, 42, 48, 55, 62, 58, 65, 70, 72, 78, 85]
product_b = [20, 25, 28, 35, 40, 38, 42, 48, 52, 55, 60, 65]
product_c = [10, 12, 15, 18, 22, 25, 28, 30, 35, 38, 42, 48]
fig, ax = plt.subplots(figsize=(12, 6))
ax.stackplot(months, product_a, product_b, product_c,
labels=['產(chǎn)品A', '產(chǎn)品B', '產(chǎn)品C'],
colors=['#3498db', '#e74c3c', '#2ecc71'], alpha=0.8)
ax.set_title('三款產(chǎn)品月度銷量趨勢', fontsize=16, fontweight='bold')
ax.legend(loc='upper left')
面積圖適合展示部分與整體的關(guān)系隨時間的變化。stackplot 是堆疊面積圖,每個系列在前一個之上疊加。
箱線圖
運行效果:

data_groups = {
'A組 (初級)': np.random.normal(60, 10, 100),
'B組 (中級)': np.random.normal(72, 12, 100),
'C組 (高級)': np.random.normal(85, 8, 100),
'D組 (專家)': np.random.normal(92, 5, 100),
}
fig, ax = plt.subplots(figsize=(10, 6))
bp = ax.boxplot(data_groups.values(), tick_labels=data_groups.keys(),
patch_artist=True, notch=True)
colors = ['#3498db', '#2ecc71', '#f39c12', '#e74c3c']
for patch, color in zip(bp['boxes'], colors):
patch.set_facecolor(color)
patch.set_alpha(0.7)
箱線圖解讀指南:

1.9 雷達圖:多維度對比
運行效果:

categories = ['攻擊力', '防御力', '速度', '智力', '耐力', '運氣']
player_stats = {
'戰(zhàn)士': [90, 85, 60, 40, 95, 50],
'法師': [45, 35, 55, 98, 40, 70],
'刺客': [80, 30, 95, 70, 45, 65],
}
angles = np.linspace(0, 2 * np.pi, len(categories), endpoint=False).tolist()
angles += angles[:1] # 閉合
fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True))
for name, stats in player_stats.items():
values = stats + stats[:1]
ax.fill(angles, values, alpha=0.15)
ax.plot(angles, values, linewidth=2, label=name)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories, fontsize=12)
ax.set_ylim(0, 100)
ax.set_title('游戲角色屬性雷達圖', fontsize=16, pad=20)
ax.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
1.10 圖表美化技巧
配色方案
# Matplotlib 內(nèi)置顏色
colors = {
'blue': '#1f77b4',
'orange': '#ff7f0e',
'green': '#2ca02c',
'red': '#d62728',
'purple': '#9467bd',
'brown': '#8c564b',
'pink': '#e377c2',
'gray': '#7f7f7f',
'olive': '#bcbd22',
'cyan': '#17becf',
}
# Seaborn 調(diào)色板(更美觀)
import seaborn as sns
palette = sns.color_palette('Set2', 6)
字體設(shè)置
plt.rcParams['font.size'] = 12 # 默認字體大小 plt.rcParams['axes.titlesize'] = 16 # 標題大小 plt.rcParams['axes.labelsize'] = 14 # 軸標簽大小 plt.rcParams['legend.fontsize'] = 11 # 圖例大小 plt.rcParams['xtick.labelsize'] = 10 # X軸刻度大小
保存圖表
plt.savefig('chart.png', dpi=150, bbox_inches='tight', transparent=False)
# dpi: 分辨率 (150=高清, 300=印刷級)
# bbox_inches='tight': 自動裁剪空白
# transparent=True: 透明背景
第二章:Seaborn —— 統(tǒng)計圖表專家
2.1 Seaborn 與 Matplotlib 的關(guān)系
Seaborn 是基于 Matplotlib 的高級封裝,提供了:
- 更美觀的默認樣式
- 更簡潔的 API
- 更好的統(tǒng)計圖表支持
- 與 Pandas DataFrame 無縫集成
pip install seaborn
import seaborn as sns import matplotlib.pyplot as plt # 設(shè)置 Seaborn 樣式 sns.set_theme(style='whitegrid', palette='Set2', font_scale=1.2)
2.2 分布圖
直方圖 + 核密度估計 (KDE)
tips = sns.load_dataset('tips')
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
# 直方圖
sns.histplot(data=tips, x='total_bill', bins=20, kde=True, ax=axes[0])
axes[0].set_title('總賬單分布 (直方圖+KDE)')
# KDE 圖
sns.kdeplot(data=tips, x='total_bill', hue='time', fill=True, ax=axes[1])
axes[1].set_title('按用餐時間的KDE')
# ECDF 圖
sns.ecdfplot(data=tips, x='total_bill', hue='day', ax=axes[2])
axes[2].set_title('經(jīng)驗累積分布函數(shù)')
plt.tight_layout()
運行效果:

箱線圖 + 小提琴圖
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
# 箱線圖
sns.boxplot(data=tips, x='day', y='total_bill', hue='sex', ax=axes[0])
axes[0].set_title('按日期和性別的賬單分布')
# 小提琴圖(顯示分布形狀)
sns.violinplot(data=tips, x='day', y='total_bill', hue='sex',
split=True, ax=axes[1])
axes[1].set_title('小提琴圖 - 分布形狀')
plt.tight_layout()
運行效果:

蜂群圖 + 箱線圖組合
fig, ax = plt.subplots(figsize=(10, 6))
sns.boxplot(data=tips, x='day', y='total_bill', color='white', ax=ax)
sns.swarmplot(data=tips, x='day', y='total_bill', color='black',
alpha=0.6, size=4, ax=ax)
ax.set_title('箱線圖 + 蜂群圖')
運行效果:

2.3 分類圖
柱狀圖
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
# 柱狀圖(帶置信區(qū)間)
sns.barplot(data=tips, x='day', y='total_bill', hue='sex', ax=axes[0])
axes[0].set_title('柱狀圖 (帶95%置信區(qū)間)')
# 計數(shù)圖
sns.countplot(data=tips, x='day', hue='sex', ax=axes[1])
axes[1].set_title('計數(shù)圖')
# 點圖(展示均值和置信區(qū)間)
sns.pointplot(data=tips, x='day', y='total_bill', hue='sex',
dodge=True, ax=axes[2])
axes[2].set_title('點圖')
plt.tight_layout()運行效果:

2.4 關(guān)系圖
散點圖矩陣
iris = sns.load_dataset('iris')
sns.pairplot(iris, hue='species', palette='Set2', diag_kind='kde')
plt.suptitle('鳶尾花數(shù)據(jù)集散點圖矩陣', y=1.02)
運行效果:

回歸散點圖
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
# 線性回歸
sns.regplot(data=tips, x='total_bill', y='tip', ax=axes[0],
scatter_kws={'alpha': 0.5})
axes[0].set_title('線性回歸擬合')
# 多項式回歸
sns.regplot(data=tips, x='total_bill', y='tip', order=2, ax=axes[1],
scatter_kws={'alpha': 0.5}, line_kws={'color': 'red'})
axes[1].set_title('多項式回歸擬合')
plt.tight_layout()
運行效果:

聯(lián)合分布圖
g = sns.jointplot(data=tips, x='total_bill', y='tip', kind='reg',
height=8, color='#3498db')
g.fig.suptitle('聯(lián)合分布圖', y=1.02)
運行效果:

2.5 矩陣圖
# 熱力圖(相關(guān)系數(shù)矩陣)
fig, ax = plt.subplots(figsize=(10, 8))
corr = tips[['total_bill', 'tip', 'size']].corr()
sns.heatmap(corr, annot=True, cmap='coolwarm', center=0,
square=True, linewidths=1, ax=ax)
ax.set_title('特征相關(guān)系數(shù)熱力圖')
# 聚類熱力圖
g = sns.clustermap(corr, cmap='coolwarm', annot=True, figsize=(8, 8))
運行效果:

第三章:Plotly —— 交互式可視化
3.1 交互式圖表的優(yōu)勢
Plotly 是一個支持交互的可視化庫。與 Matplotlib 生成的靜態(tài)圖片不同,Plotly 的圖表可以在瀏覽器中:
- 縮放:鼠標滾輪放大/縮小
- 懸停:鼠標懸停顯示數(shù)據(jù)詳情
- 平移:拖拽移動視圖
- 選擇:框選/套索選擇數(shù)據(jù)點
- 導(dǎo)出:直接保存為 PNG
pip install plotly
3.2 基礎(chǔ)交互圖
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
# Plotly Express - 最簡潔的 API
df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x='gdpPercap', y='lifeExp',
size='pop', color='continent',
hover_name='country',
log_x=True, size_max=60,
title='2007年各國GDP vs 預(yù)期壽命')
fig.show()
運行效果:

折線圖
df = px.data.stocks()
fig = px.line(df, x='date', y=['GOOG', 'AAPL', 'MSFT'],
title='科技股股價走勢',
labels={'value': '股價', 'date': '日期', 'variable': '公司'})
fig.update_layout(hovermode='x unified')
fig.show()
運行效果:

3D 散點圖
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_length',
color='species', size='petal_width',
title='鳶尾花 3D 散點圖')
fig.update_layout(margin=dict(l=0, r=0, b=0, t=40))
fig.show()
運行效果:

3.3 子圖與布局
from plotly.subplots import make_subplots
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('折線圖', '柱狀圖', '散點圖', '面積圖'),
vertical_spacing=0.12, horizontal_spacing=0.1
)
x = np.linspace(0, 10, 100)
# 折線圖
fig.add_trace(go.Scatter(x=x, y=np.sin(x), name='sin(x)'), row=1, col=1)
# 柱狀圖
fig.add_trace(go.Bar(x=['A', 'B', 'C'], y=[30, 50, 20], name='分類'), row=1, col=2)
# 散點圖
fig.add_trace(go.Scatter(x=np.random.randn(100), y=np.random.randn(100),
mode='markers', name='散點'), row=2, col=1)
# 面積圖
fig.add_trace(go.Scatter(x=x, y=np.exp(-x/3), fill='tozeroy', name='衰減'), row=2, col=2)
fig.update_layout(title_text='Plotly 子圖布局', height=700, showlegend=True)
fig.show()
運行效果:

三庫對比與選擇指南
| 特性 | Matplotlib | Seaborn | Plotly |
|---|---|---|---|
| 交互性 | 靜態(tài) | 靜態(tài) | 完全交互 |
| 代碼量 | 多 | 少 | 中等 |
| 自定義能力 | 最強 | 中等 | 強 |
| 默認美觀度 | 一般 | 很好 | 很好 |
| 學(xué)習(xí)曲線 | 中等 | 低 | 低 |
| Pandas集成 | 一般 | 優(yōu)秀 | 良好 |
| 輸出格式 | PNG/PDF/SVG | PNG/PDF/SVG | HTML/PNG |
| 適合場景 | 論文/報告 | EDA/分析 | 儀表盤/Web |
| 3D支持 | 有 | 無 | 優(yōu)秀 |
| 動畫支持 | 有 | 無 | 優(yōu)秀 |
選擇建議

最佳實踐
- 先用 Seaborn 快速探索,再用 Matplotlib 精細調(diào)整
- 交互需求用 Plotly,尤其是面向用戶的場景
- 統(tǒng)一配色方案,保持系列文章/報告的視覺一致性
- 保存高分辨率圖片(dpi ≥ 150),方便后續(xù)使用
- 圖表要有標題和標簽,讓讀者一眼理解
以上就是Python數(shù)據(jù)可視化完全指南之Matplotlib+Seaborn+Plotly用法詳解的詳細內(nèi)容,更多關(guān)于Python數(shù)據(jù)可視化的資料請關(guān)注腳本之家其它相關(guān)文章!
- Python數(shù)據(jù)可視化庫:Matplotlib、Seaborn、Plotly、Bokeh等對比與選擇
- python安裝?Matplotlib?庫和Seaborn?庫的示例詳解
- Python數(shù)據(jù)可視化之Pandas、Matplotlib與Seaborn的高效實戰(zhàn)指南
- Python繪圖工具使用Matplotlib、Seaborn和Pyecharts繪制散點圖詳解
- Python使用Matplotlib和Seaborn繪制常用圖表的技巧
- Python數(shù)據(jù)可視化之Matplotlib和Seaborn的使用教程詳解
- Python實現(xiàn)Matplotlib,Seaborn動態(tài)數(shù)據(jù)圖的示例代碼
- Python?matplotlib?seaborn繪圖教程詳解
- python可視化分析的實現(xiàn)(matplotlib、seaborn、ggplot2)
- Python AI基礎(chǔ):Matplotlib和Seaborn兩大可視化庫的原理和使用(實踐代碼)
相關(guān)文章
Python Pandas常用函數(shù)方法總結(jié)
今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著Pandas常用函數(shù)方法展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下2021-06-06
Python實現(xiàn)Word轉(zhuǎn)PDF全攻略(從入門到實戰(zhàn))
在數(shù)字化辦公場景中,Word文檔的跨平臺兼容性始終是個難題,而PDF格式憑借"所見即所得"的特性,已成為文檔分發(fā)和歸檔的標準格式,下面小編就來和大家講講如何使用Python實現(xiàn)Word轉(zhuǎn)PDF吧2025-08-08
python 內(nèi)置函數(shù)-range()+zip()+sorted()+map()+reduce()+filte
這篇文章主要介紹了python 內(nèi)置函數(shù)-range()+zip()+sorted()+map()+reduce()+filter(),想具體了解函數(shù)具體用法的小伙伴可以參考一下下面的介紹,希望對你有所幫助2021-12-12
Python 靜態(tài)導(dǎo)入與動態(tài)導(dǎo)入的實現(xiàn)示例
Python靜態(tài)導(dǎo)入和動態(tài)導(dǎo)入是指導(dǎo)入模塊或模塊內(nèi)部函數(shù)的兩種方式,本文主要介紹了Python 靜態(tài)導(dǎo)入與動態(tài)導(dǎo)入的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2024-05-05

