Skip to content

Matplotlib 完整实战手册

目录

1. 前言:简介、价值、应用场景、安装与导入验证

1.1 Matplotlib 是什么

核心说明
Matplotlib 是 Python 最基础、最强大的可视化库之一。它支持从简单折线图到 3D 图、动画图、论文级图像导出,适用于数据分析、报表制作、论文绘图、项目展示等场景。

1.2 核心价值与应用场景

核心价值

  • 通用性强:几乎所有 Python 数据可视化任务都能覆盖。
  • 可控性高:每个元素(线、点、文字、坐标轴)都可精细设置。
  • 生态兼容:与 NumPy、Pandas、Seaborn 深度协作。

典型场景

  • 数据分析可视化(趋势、对比、分布、相关性)
  • 周报/月报图表制作
  • 学术论文制图(高分辨率、矢量图)
  • Web 后端生成静态图

1.3 安装方法(pip + 镜像源)

基础安装

bash
pip install matplotlib numpy pandas

镜像安装(国内网络常用)

bash
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib numpy pandas

关键参数说明

  • -i:指定安装源地址
  • 建议和 numpy/pandas 一起安装,方便直接运行示例

1.4 标准导入方式与验证

标准导入代码示例

python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

print("matplotlib 导入成功")

导入验证代码示例

python
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [2, 4, 1])
plt.title("Matplotlib Import Test")
plt.show()
# 效果说明:弹出一个最简单折线图,表示环境可用

注意事项

  • 在脚本中看不到图像时,通常是少了 plt.show()
  • 在服务器环境可改为 plt.savefig() 导出图片。

2. 入门基础:核心概念、绘图流程、基础图形、常见误区

2.1 Matplotlib 核心概念(Figure、Axes、Axis、Artist)

核心说明

  • Figure:整张画布(可以包含多个子图)
  • Axes:一个子图区域(真正绘图的地方)
  • Axis:坐标轴对象(x 轴、y 轴)
  • Artist:图中的可见元素(线条、文字、图例等)

极简代码示例

python
import matplotlib.pyplot as plt

fig, ax = plt.subplots()          # Figure + Axes
ax.plot([1, 2, 3], [1, 4, 9])     # Artist: 折线
ax.set_title("Figure / Axes Demo")
plt.show()
# 效果说明:1个画布里有1个子图,子图中绘制1条线

2.2 基础绘图流程

核心说明
标准流程:创建画布 -> 创建子图 -> 绘制图形 -> 设置标签/标题/图例 -> 显示/保存

基础绘图完整代码示例

python
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 10, 1)
y = 2 * x + 1

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, y, label="y = 2x + 1", color="royalblue", linewidth=2)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Basic Plot Workflow")
ax.legend(loc="upper left")
ax.grid(alpha=0.3)
plt.tight_layout()
plt.show()
# 效果说明:生成带标签、标题、图例、网格的标准折线图

2.3 基础图形绘制

2.3.1 折线图(Line Plot)

功能说明:用于展示趋势变化(如时间序列)。

python
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 8)
y = np.array([10, 12, 9, 14, 18, 17, 20])

plt.figure(figsize=(7, 4))
plt.plot(x, y, marker="o", linestyle="-", color="teal", label="sales")
plt.title("Line Plot")
plt.xlabel("day")
plt.ylabel("value")
plt.legend()
plt.grid(alpha=0.2)
plt.show()

参数解释

  • marker:点标记(如 "o", "s"
  • linestyle:线型(如 "-", "--", ":"
  • color:颜色

运行效果说明

  • 图中每个点表示每日值,折线显示整体趋势。

2.3.2 散点图(Scatter Plot)

功能说明:用于观察两个变量的相关性。

python
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
x = np.random.normal(50, 10, 100)
y = x * 0.7 + np.random.normal(0, 5, 100)

plt.figure(figsize=(7, 4))
plt.scatter(x, y, c=y, cmap="viridis", alpha=0.7)
plt.title("Scatter Plot")
plt.xlabel("x")
plt.ylabel("y")
plt.colorbar(label="y intensity")
plt.show()

参数解释

  • c:点颜色映射数据
  • cmap:颜色映射方案
  • alpha:透明度(0~1)

运行效果说明

  • 点云分布越接近直线,相关性通常越强。

2.3.3 柱状图(Bar Plot)

功能说明:用于类别间对比。

python
import matplotlib.pyplot as plt

categories = ["A", "B", "C", "D"]
values = [23, 35, 30, 28]

plt.figure(figsize=(7, 4))
bars = plt.bar(categories, values, color=["#5B8FF9", "#61DDAA", "#65789B", "#F6BD16"])
plt.title("Bar Plot")
plt.xlabel("category")
plt.ylabel("value")
plt.bar_label(bars, fmt="%.0f")
plt.show()

参数解释

  • plt.bar(x, height):x 为类别,height 为数值
  • bar_label:直接在柱子上显示数值

运行效果说明

  • 通过柱高快速比较不同类别大小。

2.3.4 直方图(Histogram)

功能说明:用于观察数据分布(集中、偏态、离散程度)。

python
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
data = np.random.normal(loc=60, scale=10, size=500)

plt.figure(figsize=(7, 4))
plt.hist(data, bins=20, color="steelblue", edgecolor="white", alpha=0.9)
plt.title("Histogram")
plt.xlabel("score")
plt.ylabel("frequency")
plt.show()

参数解释

  • bins:分箱数量(越大越细)
  • edgecolor:柱边框颜色

运行效果说明

  • 形状近似钟形时,通常接近正态分布。

2.4 新手常见误区与避坑

误区1:画布和子图混淆

  • 错误:只 plt.figure() 不拿到 Axes 就混写多个图
  • 建议:优先 fig, ax = plt.subplots()

误区2:参数名写错

  • colors=(应为 color=),容易报错

误区3:图形不显示

  • 忘记 plt.show(),或在非交互环境执行

误区4:保存失败/空白图

  • plt.show() 后再 savefig 可能得到空白图(某些环境下)
  • 建议先 savefigshow

3. 核心功能与基础技巧:画布子图、样式、标签图例、图形保存

3.1 画布与子图操作

3.1.1 plt.figure() 参数设置

python
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 4), dpi=120, facecolor="#f7f7f7")
plt.plot([1, 2, 3], [3, 1, 2])
plt.title("figure() Params Demo")
plt.show()

关键参数说明

  • figsize=(w, h):画布尺寸(英寸)
  • dpi:分辨率(像素密度)
  • facecolor:背景色

3.1.2 subplot()subplots()

python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 200)

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].plot(x, np.sin(x), color="tomato")
axes[0].set_title("sin(x)")
axes[1].plot(x, np.cos(x), color="dodgerblue")
axes[1].set_title("cos(x)")
plt.tight_layout()
plt.show()

关键参数说明

  • nrows, ncols:子图行列数
  • 返回 axes 是数组,可按索引访问每个子图

3.1.3 子图布局与间距调整

python
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2, 2, figsize=(8, 6))
for i, ax in enumerate(axes.ravel(), start=1):
    ax.plot([1, 2, 3], [i, i + 1, i + 2])
    ax.set_title(f"plot {i}")

fig.subplots_adjust(wspace=0.35, hspace=0.45)
plt.show()

关键参数说明

  • wspace:子图水平间距
  • hspace:子图垂直间距
  • 也可用 plt.tight_layout() 自动调整

3.2 图形样式设置(线条、颜色、标记、透明度)

python
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0, 8)
y = x + 2

plt.figure(figsize=(8, 4))
plt.plot(
    x, y,
    color="#2E8B57",       # 颜色
    linestyle="--",        # 线型
    linewidth=2.5,         # 线宽
    marker="o",            # 点样式
    markersize=7,          # 点大小
    alpha=0.85,            # 透明度
    label="styled line"
)
plt.legend()
plt.show()

关键参数说明

  • linestyle"-", "--", "-.", ":"
  • marker"o", "s", "^", "x"
  • alpha:透明度(0 完全透明,1 不透明)

3.3 标签与图例设置

python
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y1 = [2, 3, 5, 4]
y2 = [1, 2, 2, 3]

plt.figure(figsize=(8, 4))
plt.plot(x, y1, label="Product A")
plt.plot(x, y2, label="Product B")
plt.xlabel("Quarter", fontsize=11)
plt.ylabel("Revenue", fontsize=11)
plt.title("Revenue Comparison", fontsize=13, pad=10)
plt.legend(loc="upper left", fontsize=10, frameon=True)
plt.tight_layout()
plt.show()

关键参数说明

  • fontsize:字体大小
  • loc:图例位置,如 "best", "upper right"
  • pad:标题与图距离

中文显示建议

python
import matplotlib.pyplot as plt

plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]  # Windows 常见中文字体
plt.rcParams["axes.unicode_minus"] = False             # 解决负号显示问题

3.4 图形保存(plt.savefig()

python
import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.plot([1, 2, 3], [3, 1, 2])
plt.title("Savefig Demo")

plt.savefig("demo.png", dpi=150, bbox_inches="tight")
plt.savefig("demo.jpg", dpi=200, quality=95)
plt.savefig("demo.pdf")  # 矢量图,论文常用
plt.show()

关键参数说明

  • dpi:清晰度(论文常用 300+)
  • bbox_inches="tight":自动裁剪空白边
  • 输出格式由文件后缀决定(png/jpg/pdf/svg)

注意事项

  • 批量保存时记得 plt.close(),避免内存累积。

4. 进阶技巧:高级图形、进阶子图、配色、标注注释

4.1 高级图形绘制

4.1.1 饼图(Pie)

python
import matplotlib.pyplot as plt

labels = ["Search", "Ads", "Social", "Email"]
sizes = [45, 25, 20, 10]

plt.figure(figsize=(6, 6))
plt.pie(
    sizes,
    labels=labels,
    autopct="%1.1f%%",
    startangle=90,
    pctdistance=0.75,
    wedgeprops={"edgecolor": "white"}
)
plt.title("Channel Share")
plt.show()

参数解释

  • autopct:百分比格式
  • startangle:起始角度
  • wedgeprops:扇区样式

4.1.2 箱线图(Boxplot)

python
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
data = [np.random.normal(60, 8, 100), np.random.normal(70, 10, 100)]

plt.figure(figsize=(7, 4))
plt.boxplot(data, labels=["Class A", "Class B"], patch_artist=True)
plt.title("Boxplot")
plt.ylabel("Score")
plt.show()

场景说明

  • 用于对比分布、中位数、异常值,特别适合实验数据分析。

4.1.3 热力图(Heatmap,纯 Matplotlib)

python
import matplotlib.pyplot as plt
import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6], [6, 8, 9]])

plt.figure(figsize=(6, 5))
im = plt.imshow(matrix, cmap="YlGnBu")
plt.colorbar(im, label="value")
plt.xticks([0, 1, 2], ["A", "B", "C"])
plt.yticks([0, 1, 2], ["X", "Y", "Z"])
plt.title("Heatmap")
plt.show()

4.1.4 雷达图(Radar)

python
import matplotlib.pyplot as plt
import numpy as np

labels = np.array(["Speed", "Power", "Skill", "Team", "Stable"])
scores = np.array([80, 65, 78, 90, 72])
scores = np.concatenate([scores, [scores[0]]])

angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False)
angles = np.concatenate([angles, [angles[0]]])

fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111, polar=True)
ax.plot(angles, scores, "o-", linewidth=2)
ax.fill(angles, scores, alpha=0.25)
ax.set_thetagrids(angles[:-1] * 180 / np.pi, labels)
ax.set_title("Radar Chart")
plt.show()

4.1.5 3D 图(Surface)

python
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401

x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(111, projection="3d")
surf = ax.plot_surface(X, Y, Z, cmap="viridis", edgecolor="none")
fig.colorbar(surf, shrink=0.6)
ax.set_title("3D Surface")
plt.show()

4.2 子图进阶(嵌套、不规则布局、共享坐标轴)

4.2.1 不规则布局(GridSpec)

python
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10, 6))
gs = fig.add_gridspec(2, 3)

ax1 = fig.add_subplot(gs[0, :])   # 第一行占满
ax2 = fig.add_subplot(gs[1, 0])
ax3 = fig.add_subplot(gs[1, 1:])

ax1.plot([1, 2, 3], [1, 4, 2]); ax1.set_title("Top")
ax2.bar(["A", "B", "C"], [3, 5, 2]); ax2.set_title("Bottom Left")
ax3.scatter([1, 2, 3], [2, 1, 3]); ax3.set_title("Bottom Right")
plt.tight_layout()
plt.show()

4.2.2 共享坐标轴

python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(8, 5))
axes[0].plot(x, np.sin(x)); axes[0].set_title("sin")
axes[1].plot(x, np.cos(x), color="tomato"); axes[1].set_title("cos")
plt.tight_layout()
plt.show()

参数说明

  • sharex=True:共享 x 轴,便于对比趋势

4.3 颜色与配色方案

python
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y = [4, 7, 3, 8, 6]

plt.figure(figsize=(8, 4))
plt.bar(x - 0.2, y, width=0.4, color="skyblue", label="named color")
plt.bar(x + 0.2, np.array(y) - 1, width=0.4, color="#FF7F50", label="hex color")
plt.title("Color Demo")
plt.legend()
plt.show()

配色技巧

  • 分类型数据:使用高区分度颜色(如 tab10
  • 连续型数据:使用渐变色(如 viridis, plasma
  • 论文图:优先低饱和度,减少视觉噪声

4.4 图形标注与注释(annotate / text

python
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 3, 7, 6]

plt.figure(figsize=(8, 4))
plt.plot(x, y, marker="o")
plt.text(1, 2.2, "start", fontsize=10, color="gray")
plt.annotate(
    "peak",
    xy=(4, 7), xytext=(3.2, 7.8),
    arrowprops=dict(arrowstyle="->", color="red"),
    fontsize=11, color="red"
)
plt.title("Annotation Demo")
plt.show()

注意事项

  • xy 是被标注点,xytext 是文字位置。
  • 论文图常用注释解释峰值和异常点。

5. 实战场景:分析、论文、动画、多图组合、美化

5.1 数据分析可视化(Pandas + NumPy + Matplotlib)

python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

np.random.seed(1)
dates = pd.date_range("2026-01-01", periods=30, freq="D")
sales = np.random.randint(80, 180, size=30)
cost = np.random.randint(50, 120, size=30)

df = pd.DataFrame({"date": dates, "sales": sales, "cost": cost})
df["profit"] = df["sales"] - df["cost"]

fig, axes = plt.subplots(2, 1, figsize=(10, 6), sharex=True)
axes[0].plot(df["date"], df["sales"], label="sales")
axes[0].plot(df["date"], df["cost"], label="cost")
axes[0].legend(); axes[0].set_title("Sales & Cost")

axes[1].bar(df["date"], df["profit"], color="seagreen")
axes[1].set_title("Profit")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

场景解读

  • 上图比较收入成本,下图看利润波动,适合业务周报。

5.2 论文/报告绘图模板

python
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = 11

x = np.linspace(0, 10, 200)
y = np.exp(-x / 3) * np.sin(2 * x)

plt.figure(figsize=(6, 4), dpi=300)
plt.plot(x, y, linewidth=1.8, color="black")
plt.xlabel("Time (s)")
plt.ylabel("Amplitude")
plt.title("Damped Oscillation")
plt.grid(alpha=0.2)
plt.tight_layout()
plt.savefig("paper_figure.pdf")   # 矢量图
plt.savefig("paper_figure.png", dpi=300)
plt.show()

场景解读

  • 论文优先导出 pdf/svg(矢量)+ png(300dpi)(投稿系统兼容)。

5.3 动态图绘制(matplotlib.animation

python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots(figsize=(7, 4))
x = np.linspace(0, 2 * np.pi, 400)
line, = ax.plot(x, np.sin(x))
ax.set_ylim(-1.2, 1.2)
ax.set_title("Sine Wave Animation")

def update(frame):
    line.set_ydata(np.sin(x + frame / 10))
    return line,

ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)
plt.show()

# 可选保存(需要 pillow):
# ani.save("sine.gif", writer="pillow", fps=20)

参数说明

  • frames:总帧数
  • interval:每帧间隔(毫秒)
  • blit=True:减少重绘,提升流畅度

5.4 多图形组合展示(同画布多类型)

python
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
x = np.arange(1, 11)
y = np.random.randint(10, 40, 10)

fig, axes = plt.subplots(1, 3, figsize=(14, 4))
axes[0].plot(x, y, marker="o"); axes[0].set_title("Line")
axes[1].bar(x, y, color="cornflowerblue"); axes[1].set_title("Bar")
axes[2].scatter(x, y, c=y, cmap="plasma"); axes[2].set_title("Scatter")
plt.tight_layout()
plt.show()

5.5 图形美化技巧

python
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [5, 7, 6, 9, 8]

plt.figure(figsize=(8, 4))
plt.plot(x, y, linewidth=2.5, color="#2F4F4F")
plt.grid(linestyle="--", alpha=0.3)
plt.tick_params(axis="both", labelsize=10)

ax = plt.gca()
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)

plt.title("Beautified Chart")
plt.tight_layout()
plt.show()

效果说明

  • 去掉顶部/右侧边框后,图形更简洁,报告场景常用。

6. 高级进阶:Seaborn联动、批量绘图、自定义样式、导出转换

6.1 Matplotlib 与 Seaborn 联动(对比示例)

python
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

np.random.seed(0)
data = np.random.normal(0, 1, 300)

fig, axes = plt.subplots(1, 2, figsize=(10, 4))

# Matplotlib
axes[0].hist(data, bins=20, color="skyblue", edgecolor="white")
axes[0].set_title("Matplotlib Hist")

# Seaborn(底层仍基于 Matplotlib)
sns.histplot(data, bins=20, kde=True, ax=axes[1], color="tomato")
axes[1].set_title("Seaborn Hist + KDE")

plt.tight_layout()
plt.show()

场景建议

  • 需要精细控制:优先 Matplotlib
  • 需要快速美观:可先 Seaborn,再用 Matplotlib 微调

6.2 批量绘图与批量保存

python
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)

for i in range(5):
    data = np.random.normal(loc=i * 10, scale=5, size=300)
    plt.figure(figsize=(6, 4))
    plt.hist(data, bins=20, color="steelblue", alpha=0.85)
    plt.title(f"Batch Histogram {i}")
    plt.tight_layout()
    plt.savefig(f"batch_hist_{i}.png", dpi=150)
    plt.close()

注意事项

  • 批量任务必须 plt.close(),否则容易卡顿和内存上涨。

6.3 自定义图形样式(坐标轴、图例、颜色映射)

python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 50)
y = np.sin(x)

fig, ax = plt.subplots(figsize=(8, 4))
sc = ax.scatter(x, y, c=x, cmap="coolwarm", s=60)
ax.set_title("Custom Style")
ax.set_xlabel("X Value")
ax.set_ylabel("Y Value")
ax.legend(["sin(x)"], loc="lower left", frameon=False)
ax.spines["left"].set_linewidth(1.2)
ax.spines["bottom"].set_linewidth(1.2)
fig.colorbar(sc, ax=ax, label="x intensity")
plt.show()

6.4 图形导出与格式转换

python
import matplotlib.pyplot as plt

plt.figure(figsize=(6, 4))
plt.plot([0, 1, 2], [1, 3, 2], linewidth=2)
plt.title("Export Demo")

plt.savefig("export_png.png", dpi=200)
plt.savefig("export_svg.svg")   # 矢量图,缩放不失真
plt.savefig("export_pdf.pdf")   # 论文/打印常用
plt.show()

导出建议

  • 屏幕展示:pngdpi=120~200
  • 打印/论文:pdf/svgpng dpi>=300

7. 核心工具与资源:参数手册、模板库、学习资源

7.1 Matplotlib 常用参数手册(可速查)

plt.plot() 常用参数

  • x, y:横纵坐标数据
  • color:线颜色
  • linestyle:线型(-, --, :, -.
  • linewidth:线宽
  • marker:点样式
  • label:图例名称
  • alpha:透明度

plt.scatter() 常用参数

  • s:点大小
  • c:颜色或颜色映射值
  • cmap:颜色映射方案
  • alpha:透明度

plt.bar() 常用参数

  • width:柱宽
  • color:柱颜色
  • edgecolor:边框颜色

plt.savefig() 常用参数

  • fname:文件名(含后缀)
  • dpi:分辨率
  • bbox_inches:边距裁剪
  • transparent:透明背景

7.2 优质绘图模板(可直接复用)

模板1:分析折线图

python
import matplotlib.pyplot as plt

def line_template(x, y, title="Line Chart", xlabel="x", ylabel="y"):
    plt.figure(figsize=(8, 4))
    plt.plot(x, y, marker="o", linewidth=2)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.grid(alpha=0.25)
    plt.tight_layout()
    plt.show()

模板2:论文风格图

python
import matplotlib.pyplot as plt

def paper_style():
    plt.rcParams["font.family"] = "Times New Roman"
    plt.rcParams["font.size"] = 11
    plt.rcParams["axes.linewidth"] = 1.0

模板3:批量保存模板

python
import matplotlib.pyplot as plt

def save_plot(name: str, dpi: int = 300):
    plt.tight_layout()
    plt.savefig(name, dpi=dpi, bbox_inches="tight")
    plt.close()

7.3 学习资源推荐


8. 常见问题与避坑指南:错误修复与性能优化

8.1 高频问题修复

问题1:图形显示空白

错误代码

python
import matplotlib.pyplot as plt
plt.figure()
plt.show()
plt.plot([1, 2, 3], [1, 4, 2])  # show 后再画,结果空白

修正代码

python
import matplotlib.pyplot as plt
plt.figure()
plt.plot([1, 2, 3], [1, 4, 2])
plt.show()

原因说明:绘图语句应在 show() 之前执行。

问题2:坐标轴刻度异常拥挤

修正代码

python
import matplotlib.pyplot as plt

x = [f"2026-01-{i:02d}" for i in range(1, 16)]
y = list(range(15))
plt.plot(x, y)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

原因说明:标签过密需旋转并调整布局。

问题3:图形保存模糊

修正代码

python
plt.savefig("high_quality.png", dpi=300, bbox_inches="tight")

原因说明:默认 dpi 较低,需主动提升分辨率。

8.2 高级避坑技巧(性能与环境)

  • 大数据量折线可先降采样(如每 10 个点取 1 个)
  • 批量绘图时关闭交互并及时 plt.close()
  • Jupyter 中图太多时可分批展示,避免前端卡顿
  • 服务器环境可使用无界面后端:
python
import matplotlib
matplotlib.use("Agg")  # 无 GUI 环境下渲染并保存

9. 实战案例汇总(3-5个完整案例)

案例1:销售趋势分析图(数据准备 -> 绘图 -> 优化 -> 导出)

python
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({
    "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    "sales": [120, 135, 150, 148, 170, 180]
})

plt.figure(figsize=(8, 4))
plt.plot(df["month"], df["sales"], marker="o", linewidth=2, color="royalblue")
plt.title("Monthly Sales Trend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.grid(alpha=0.25)
plt.tight_layout()
plt.savefig("case1_sales_trend.png", dpi=200)
plt.show()

效果说明:适合运营周报/月报趋势展示。

案例2:学生成绩分布(直方图 + 箱线图)

python
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(7)
scores = np.random.normal(75, 12, 300)

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].hist(scores, bins=20, color="#4C78A8", alpha=0.9)
axes[0].set_title("Score Histogram")
axes[1].boxplot(scores, vert=True, patch_artist=True)
axes[1].set_title("Score Boxplot")
plt.tight_layout()
plt.savefig("case2_score_distribution.pdf")
plt.show()

效果说明:左图看分布,右图看异常值和中位数。

案例3:相关性热力图(矩阵可视化)

python
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(10)
data = np.random.rand(5, 5)
corr = np.corrcoef(data)

plt.figure(figsize=(6, 5))
im = plt.imshow(corr, cmap="coolwarm", vmin=-1, vmax=1)
plt.colorbar(im, label="correlation")
plt.title("Correlation Heatmap")
plt.tight_layout()
plt.savefig("case3_corr_heatmap.png", dpi=300)
plt.show()

效果说明:用于特征相关性探索与报告展示。

案例4:论文级多子图结果对比

python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 200)

fig, axes = plt.subplots(2, 2, figsize=(8, 6), dpi=300, sharex=True)
axes[0, 0].plot(x, np.sin(x)); axes[0, 0].set_title("sin")
axes[0, 1].plot(x, np.cos(x)); axes[0, 1].set_title("cos")
axes[1, 0].plot(x, np.sin(2 * x)); axes[1, 0].set_title("sin(2x)")
axes[1, 1].plot(x, np.cos(2 * x)); axes[1, 1].set_title("cos(2x)")

for ax in axes.ravel():
    ax.grid(alpha=0.2)

plt.tight_layout()
plt.savefig("case4_paper_subplots.svg")
plt.show()

效果说明:适合实验结果对比展示,可直接用于论文附图。

案例5:动态监控曲线(动画)

python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots(figsize=(8, 4))
x = np.linspace(0, 4 * np.pi, 300)
line, = ax.plot(x, np.sin(x), color="tomato")
ax.set_ylim(-1.2, 1.2)
ax.set_title("Real-time Like Monitoring")

def update(frame):
    line.set_ydata(np.sin(x + frame * 0.1))
    return line,

ani = FuncAnimation(fig, update, frames=60, interval=80, blit=True)
plt.show()

效果说明:可用于演示实时监控或模型迭代过程。


10. 运行环境与依赖说明

10.1 推荐环境

  • Python 3.9+
  • matplotlib 3.7+
  • numpy 1.24+
  • pandas 2.0+
  • seaborn 0.12+(联动章节使用)

10.2 一键安装命令

bash
pip install matplotlib numpy pandas seaborn pillow

10.3 运行步骤

  1. 安装依赖
  2. 复制示例代码到 .py 文件
  3. 执行 python your_script.py
  4. 按需查看图像或导出文件

11. 总结

关键结论

  • Matplotlib 学习主线是:基础图形 -> 样式控制 -> 子图布局 -> 场景化实战 -> 导出规范
  • 真正实战能力来自“可复用模板 + 参数理解 + 批量化处理”。
  • 遇到问题先检查:数据、坐标轴、布局、保存参数、运行环境,大多数异常都能快速定位。