🕐 预计用时:3-4 小时 | 🎯 目标:掌握折线图、柱状图、散点图、饼图、子图和样式定制
Matplotlib 是 Python 最基础、最强大的绘图库。几乎所有 Python 数据可视化工具(Seaborn、Pandas 绘图、Plotly)都基于它。
# 安装
# pip install matplotlib
# 核心模块
import matplotlib.pyplot as plt # 绘图用这个
import numpy as np
import pandas as pd
# 支持中文显示(必须设置!)
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False # 负号显示
# 为什么用 Matplotlib?
# Excel 图表:好看但难自动化
# Matplotlib:完全代码控制,可复现,可批量生成,可定制到像素级⚠️ 中文显示问题(必做!)
Matplotlib 默认不支持中文,必须在代码开头设置字体:plt.rcParams['font.sans-serif'] = ['SimHei']
如果 SimHei 不可用,尝试:['Microsoft YaHei', 'WenQuanYi Micro Hei', 'Arial Unicode MS']
# Matplotlib 的两套 API
# 1. pyplot 接口(简单,类似 MATLAB)→ plt.xxx()
# 2. 面向对象接口(灵活,推荐)→ fig, ax = plt.subplots()
# 两者关系:每个 plt 操作背后都是对 Figure 和 Axes 对象的操作
# 最简示例
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.title('简单折线图')
plt.xlabel('X 轴')
plt.ylabel('Y 轴')
plt.show() # 显示图表(Jupyter 中用 %matplotlib inline)
# 面向对象写法(推荐)
fig, ax = plt.subplots() # 创建 Figure 和 Axes
ax.plot([1, 2, 3, 4], [1, 4, 9, 16])
ax.set_title('简单折线图')
ax.set_xlabel('X 轴')
ax.set_ylabel('Y 轴')
plt.show()折线图是最常用的图表——展示数据随时间或顺序的变化趋势。
import matplotlib.pyplot as plt
import numpy as np
# 基础折线图
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
fig, ax = plt.subplots(figsize=(10, 6)) # 10英寸宽,6英寸高
ax.plot(x, y1, label='sin(x)', color='#07c160', linewidth=2)
ax.plot(x, y2, label='cos(x)', color='#ff6b6b', linewidth=2, linestyle='--')
ax.set_title('三角函数图像', fontsize=16, fontweight='bold')
ax.set_xlabel('x', fontsize=12)
ax.set_ylabel('y', fontsize=12)
ax.legend(fontsize=12) # 图例
ax.grid(True, alpha=0.3) # 网格线
ax.set_xlim(0, 10) # X 轴范围
ax.set_ylim(-1.5, 1.5) # Y 轴范围
plt.tight_layout() # 自动调整布局
plt.savefig('sine_cosine.png', dpi=150, bbox_inches='tight') # 保存图片
plt.show()# 多条折线对比
months = ['1月', '2月', '3月', '4月', '5月', '6月']
sales_a = [120, 135, 148, 162, 175, 190]
sales_b = [90, 105, 115, 128, 140, 155]
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(months, sales_a, marker='o', markersize=8, linewidth=2,
color='#07c160', label='产品A')
ax.plot(months, sales_b, marker='s', markersize=8, linewidth=2,
color='#ff6b6b', label='产品B')
# 在数据点上标注数值
for i, (a, b) in enumerate(zip(sales_a, sales_b)):
ax.annotate(str(a), (i, a), textcoords="offset points",
xytext=(0, 10), ha='center', fontsize=9)
ax.annotate(str(b), (i, b), textcoords="offset points",
xytext=(0, -15), ha='center', fontsize=9)
ax.set_title('2026年上半年产品销量对比', fontsize=16)
ax.set_xlabel('月份')
ax.set_ylabel('销量(件)')
ax.legend()
ax.grid(True, alpha=0.3, linestyle='--')
plt.tight_layout()
plt.show()color | 'red''#07c160'(0.1,0.5,0.8) | |
linewidth | 2 | |
linestyle | '-''--' 虚线 ':' 点线 | |
marker | 'o''s' 方 '^' 三角 '*' 星 | |
markersize | 8 | |
label | '销量' | |
alpha | 0.7 |
柱状图适合比较不同类别的数据大小。
# 基础柱状图
categories = ['Python', 'Java', 'JavaScript', 'C++', 'Go']
popularity = [35, 25, 20, 12, 8]
fig, ax = plt.subplots(figsize=(10, 6))
bars = ax.bar(categories, popularity, color=['#07c160', '#ff6b6b', '#ffd93d', '#6bcb77', '#4d96ff'])
# 在柱子顶部标注数值
for bar, val in zip(bars, popularity):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
f'{val}%', ha='center', fontsize=11, fontweight='bold')
ax.set_title('2026年编程语言流行度', fontsize=16)
ax.set_ylabel('流行度 (%)')
ax.set_ylim(0, 45)
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
# 水平柱状图
fig, ax = plt.subplots(figsize=(10, 6))
ax.barh(categories, popularity, color=['#07c160', '#ff6b6b', '#ffd93d', '#6bcb77', '#4d96ff'])
ax.set_xlabel('流行度 (%)')
ax.set_title('2026年编程语言流行度(水平)')
plt.tight_layout()
plt.show()# 分组柱状图(对比多个维度)
x = np.arange(len(categories))
width = 0.35
fig, ax = plt.subplots(figsize=(12, 6))
popularity_2025 = [30, 28, 22, 14, 6]
popularity_2026 = [35, 25, 20, 12, 8]
bars1 = ax.bar(x - width/2, popularity_2025, width, label='2025', color='#4d96ff')
bars2 = ax.bar(x + width/2, popularity_2026, width, label='2026', color='#07c160')
ax.set_xticks(x)
ax.set_xticklabels(categories)
ax.set_ylabel('流行度 (%)')
ax.set_title('编程语言流行度对比:2025 vs 2026')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
# 堆叠柱状图
fig, ax = plt.subplots(figsize=(12, 6))
q1 = [30, 20, 15, 10, 5]
q2 = [35, 25, 20, 12, 8]
ax.bar(categories, q1, label='Q1', color='#4d96ff')
ax.bar(categories, q2, bottom=q1, label='Q2', color='#07c160')
ax.set_ylabel('销量')
ax.set_title('季度销量堆叠图')
ax.legend()
plt.tight_layout()
plt.show()散点图适合展示两个变量之间的关系(相关性)。
# 基础散点图
np.random.seed(42)
x = np.random.randn(100)
y = 2 * x + np.random.randn(100) * 0.5
fig, ax = plt.subplots(figsize=(10, 6))
scatter = ax.scatter(x, y, c=y, cmap='viridis', s=50, alpha=0.7, edgecolors='white')
ax.set_title('散点图:X vs Y', fontsize=16)
ax.set_xlabel('X 值')
ax.set_ylabel('Y 值')
plt.colorbar(scatter, label='Y 值') # 颜色条
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# 气泡图(散点 + 大小)
np.random.seed(42)
x = np.random.randn(50)
y = np.random.randn(50)
sizes = np.random.randint(50, 500, 50) # 气泡大小
colors = np.random.randn(50) # 颜色
fig, ax = plt.subplots(figsize=(10, 6))
scatter = ax.scatter(x, y, s=sizes, c=colors, cmap='RdYlGn',
alpha=0.6, edgecolors='gray')
ax.set_title('气泡图:大小表示销量,颜色表示利润率')
ax.set_xlabel('广告投入')
ax.set_ylabel('销售额')
plt.colorbar(scatter, label='利润率')
plt.tight_layout()
plt.show()# 带回归线的散点图
np.random.seed(42)
x = np.random.uniform(10, 50, 50) # 广告投入
y = 3 * x + 20 + np.random.randn(50) * 15 # 销售额
fig, ax = plt.subplots(figsize=(10, 6))
ax.scatter(x, y, s=60, alpha=0.7, color='#07c160', edgecolors='white', label='数据点')
# 拟合直线
coefficients = np.polyfit(x, y, 1) # 1次多项式拟合
poly = np.poly1d(coefficients)
x_line = np.linspace(x.min(), x.max(), 100)
ax.plot(x_line, poly(x_line), color='#ff6b6b', linewidth=2, linestyle='--',
label=f'拟合线: y={coefficients[0]:.1f}x+{coefficients[1]:.1f}')
# 计算 R²
y_pred = poly(x)
ss_res = np.sum((y - y_pred) ** 2)
ss_tot = np.sum((y - np.mean(y)) ** 2)
r_squared = 1 - ss_res / ss_tot
ax.text(0.05, 0.95, f'R² = {r_squared:.3f}', transform=ax.transAxes,
fontsize=12, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
ax.set_title('广告投入与销售额的相关性', fontsize=16)
ax.set_xlabel('广告投入(万元)')
ax.set_ylabel('销售额(万元)')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()# 基础饼图
labels = ['Python', 'Java', 'JavaScript', 'C++', '其他']
sizes = [35, 25, 20, 12, 8]
colors = ['#07c160', '#ff6b6b', '#ffd93d', '#4d96ff', '#cccccc']
explode = (0.05, 0, 0, 0, 0) # Python 突出显示
fig, ax = plt.subplots(figsize=(8, 8))
wedges, texts, autotexts = ax.pie(
sizes,
explode=explode,
labels=labels,
colors=colors,
autopct='%1.1f%%', # 显示百分比
shadow=True, # 阴影
startangle=90, # 起始角度
textprops={'fontsize': 12}
)
# 设置百分比文字样式
for autotext in autotexts:
autotext.set_fontweight('bold')
autotext.set_color('white')
ax.set_title('编程语言市场份额', fontsize=16, fontweight='bold')
plt.tight_layout()
plt.show()
# 环形图(甜甜圈图)
fig, ax = plt.subplots(figsize=(8, 8))
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%',
pctdistance=0.85, wedgeprops=dict(width=0.4)) # width 控制环的宽度
# 中心文字
ax.text(0, 0, '编程语言\n市场份额', ha='center', va='center',
fontsize=14, fontweight='bold')
ax.set_title('编程语言市场份额(环形图)', fontsize=16)
plt.tight_layout()
plt.show()直方图展示数据的分布情况——哪些值出现频率高,哪些低。
# 正态分布直方图
np.random.seed(42)
data = np.random.normal(170, 8, 1000) # 身高:均值170cm,标准差8cm
fig, ax = plt.subplots(figsize=(10, 6))
ax.hist(data, bins=30, color='#07c160', edgecolor='white', alpha=0.8)
ax.axvline(np.mean(data), color='red', linestyle='--', linewidth=2,
label=f'均值: {np.mean(data):.1f}cm')
ax.axvline(np.median(data), color='blue', linestyle='--', linewidth=2,
label=f'中位数: {np.median(data):.1f}cm')
ax.set_title('1000人身高分布', fontsize=16)
ax.set_xlabel('身高 (cm)')
ax.set_ylabel('频数')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
# 多组对比直方图
np.random.seed(42)
male = np.random.normal(175, 7, 500)
female = np.random.normal(162, 6, 500)
fig, ax = plt.subplots(figsize=(10, 6))
ax.hist(male, bins=30, alpha=0.6, color='#4d96ff', label='男性', edgecolor='white')
ax.hist(female, bins=30, alpha=0.6, color='#ff6b6b', label='女性', edgecolor='white')
ax.set_title('男女身高分布对比', fontsize=16)
ax.set_xlabel('身高 (cm)')
ax.set_ylabel('频数')
ax.legend()
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()# 箱线图:展示数据的五数概括(最小值、Q1、中位数、Q3、最大值)
np.random.seed(42)
data = {
'Python': np.random.normal(85, 10, 50),
'Java': np.random.normal(78, 15, 50),
'JavaScript': np.random.normal(82, 12, 50),
'C++': np.random.normal(70, 20, 50),
}
fig, ax = plt.subplots(figsize=(10, 6))
bp = ax.boxplot(data.values(), labels=data.keys(), patch_artist=True)
# 设置颜色
colors = ['#07c160', '#ff6b6b', '#ffd93d', '#4d96ff']
for patch, color in zip(bp['boxes'], colors):
patch.set_facecolor(color)
patch.set_alpha(0.7)
# 标注中位数
for median in bp['medians']:
median.set_color('red')
median.set_linewidth(2)
ax.set_title('各语言考试成绩分布', fontsize=16)
ax.set_ylabel('成绩')
ax.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
# 箱线图各部分含义:
# 箱子中间的红线 = 中位数(50%分位数)
# 箱子的上下边 = Q1(25%)和 Q3(75%)
# 箱子的高度 = IQR = Q3 - Q1(四分位距)
# 上下须线 = Q3 + 1.5*IQR 和 Q1 - 1.5*IQR
# 圆点 = 离群值(超出须线的数据点)💡 箱线图怎么看?
• 箱子高 → 数据分散(方差大)
• 箱子矮 → 数据集中(方差小)
• 中位线偏上 → 左偏分布(多数人成绩高)
• 中位线偏下 → 右偏分布(多数人成绩低)
• 圆点多 → 离群值多,数据质量需要关注
# 方法1:plt.subplots() 创建网格
fig, axes = plt.subplots(2, 2, figsize=(12, 10)) # 2行2列
# 左上:折线图
x = np.linspace(0, 10, 100)
axes[0, 0].plot(x, np.sin(x), color='#07c160')
axes[0, 0].set_title('正弦函数')
axes[0, 0].grid(True, alpha=0.3)
# 右上:柱状图
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 12, 67]
axes[0, 1].bar(categories, values, color='#ff6b6b')
axes[0, 1].set_title('柱状图')
# 左下:散点图
axes[1, 0].scatter(np.random.randn(50), np.random.randn(50), color='#4d96ff')
axes[1, 0].set_title('散点图')
# 右下:饼图
axes[1, 1].pie([30, 25, 20, 25], labels=['A', 'B', 'C', 'D'], autopct='%1.0f%%')
axes[1, 1].set_title('饼图')
fig.suptitle('四种图表对比', fontsize=18, fontweight='bold')
plt.tight_layout()
plt.show()
# 方法2:不规则布局(GridSpec)
from matplotlib.gridspec import GridSpec
fig = plt.figure(figsize=(14, 6))
gs = GridSpec(1, 3, figure=fig)
# 左边大图占 2 列
ax1 = fig.add_subplot(gs[0, 0:2])
ax1.plot(x, np.sin(x), color='#07c160', linewidth=2)
ax1.set_title('大图:折线图')
# 右边小图
ax2 = fig.add_subplot(gs[0, 2])
ax2.bar(categories, values, color='#ff6b6b')
ax2.set_title('小图:柱状图')
plt.tight_layout()
plt.show()# === 内置样式(一行代码变好看)===
plt.style.use('seaborn-v0_8') # Seaborn 风格
# plt.style.use('ggplot') # R 语言 ggplot 风格
# plt.style.use('dark_background') # 暗色背景
# plt.style.use('fivethirtyeight') # 新闻网站风格
# 查看所有可用样式
print(plt.style.available)
# === 自定义颜色方案 ===
COLORS = {
'primary': '#07c160', # 微信绿
'danger': '#ff6b6b', # 红色
'warning': '#ffd93d', # 黄色
'info': '#4d96ff', # 蓝色
'gray': '#888888',
}
# === 全局样式设置 ===
plt.rcParams.update({
'figure.figsize': (10, 6),
'figure.dpi': 100,
'font.size': 12,
'axes.titlesize': 16,
'axes.labelsize': 12,
'axes.grid': True,
'grid.alpha': 0.3,
'lines.linewidth': 2,
'lines.markersize': 6,
})
# === 保存高质量图片 ===
# PNG 格式(适合网页)
plt.savefig('chart.png', dpi=150, bbox_inches='tight', facecolor='white')
# PDF 格式(适合论文)
plt.savefig('chart.pdf', bbox_inches='tight')
# SVG 格式(矢量图,放大不失真)
plt.savefig('chart.svg', bbox_inches='tight')
# === 清除和关闭 ===
plt.clf() # 清除当前图形
plt.close() # 关闭图形窗口(释放内存)
plt.close('all') # 关闭所有窗口💡 专业图表的 5 个要素:
1. 标题:让人一眼知道图表在说什么
2. 轴标签:X 轴和 Y 轴分别代表什么
3. 图例:多条线/多种颜色时必须有
4. 网格线:帮助读数,但不要太抢眼(alpha=0.3)
5. 数据标注:关键数据点直接标注数值
# 创建 12 个月的销售数据,画折线图:
# - 两条线(线上/线下)
# - 标注最高点和最低点
# - 添加图例、标题、网格线# 用子图布局(2x2)展示:
# - 左上:成绩直方图
# - 右上:各科箱线图
# - 左下:男女成绩对比柱状图
# - 右下:成绩等级饼图# 创建一个自定义颜色方案,画出一组专业图表:
# - 使用统一的配色(5种颜色)
# - 设置全局字体和大小
# - 保存为 PNG 和 PDFax.plot() | ||
ax.bar()ax.barh() | ||
ax.scatter() | ||
ax.pie() | ||
ax.hist() | ||
ax.boxplot() | ||
fig, axes = plt.subplots() |
🚀 明日预告:Day 77 — Seaborn 可视化
Matplotlib 功能强大但代码量多。Seaborn 在它之上封装了更高级的 API——一行代码画出漂亮的分布图、热力图、分类图。数据分析师的首选可视化工具!