入门
安装与第一个图形
pip install matplotlib 安装完整的 matplotlib 发行版(包含 pyplot 接口)。约定用 import matplotlib.pyplot as plt,几乎所有教程和示例都使用此别名。plt.show() 会阻塞直到关闭窗口;在 Jupyter 中 %matplotlib inline 将图形内嵌到输出单元格,%matplotlib widget 则启用交互式图形。
# install
pip install matplotlib
import matplotlib.pyplot as plt
import numpy as np
# a simple line plot
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.show()pyplot 状态式接口
pyplot 是一个状态机接口:它跟踪'当前图形'和'当前坐标轴',plt.plot() 等函数会作用于当前坐标轴,没有则自动创建一个。这种风格适合快速原型和交互式使用,但在程序化代码中面向对象的风格(fig, ax = plt.subplots())更清晰、更可控,尤其是在处理多个子图时。
import matplotlib.pyplot as plt
# pyplot tracks the "current" figure and axes
plt.figure() # create a new figure
plt.plot([1, 2, 3], [4, 5, 2])
plt.title("State-based") # applies to the current axes
plt.xlim(0, 4)
plt.ylim(0, 6)
plt.show()
# plt.gcf() -> current figure, plt.gca() -> current axes
print(plt.gca())Figure 与 Axes(面向对象接口)
Figure 是顶层容器,容纳一个或多个 Axes、颜色条、图例、文本等。Axes 是带有坐标轴的实际绘图区域。面向对象风格(用 ax.plot() 而非 plt.plot())显式控制哪个坐标轴,这是库代码和复杂图形的推荐风格。 一个 Figure 可包含多个用 add_subplot 或 subplots 添加的 Axes。
import matplotlib.pyplot as plt
import numpy as np
# object-oriented interface: explicit Figure and Axes objects
fig, ax = plt.subplots() # fig is the canvas, ax is a single Axes
x = np.linspace(0, 5, 50)
ax.plot(x, x**2, label="x^2")
ax.plot(x, x**3, label="x^3")
ax.set_title("OO Interface")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()常用导入与约定
np.linspace 创建均匀间隔的采样,非常适合折线图。约定:plt 是 pyplot 的标准别名,np 是 numpy 的别名。这两个别名在整个生态系统中是通用的——保持使用它们可让你的代码可读且对其他人友好。arr.shape 检查数组的维度;大多数绘图函数接受 1-D 数组并按顺序配对 (x, y) 值。
# the universal alias
import matplotlib.pyplot as plt
import numpy as np
# for the OO interface you often see
from matplotlib.figure import Figure
from matplotlib.axes import Axes
# set a global style once
plt.rcParams["figure.dpi"] = 100
plt.rcParams["font.size"] = 11
# inline backend in Jupyter (not needed in scripts)
# %matplotlib inline后端与 plt.show()
matplotlib 通过'后端'将图形渲染到屏幕或文件。交互式后端(Qt5Agg、TkAgg、MacOSX)打开 GUI 窗口;内联后端(SVG、notebook)在 Jupyter 中渲染。plt.show() 触发 GUI 事件循环并显示所有打开的图形——它应该通常是脚本的最后一行。plt.savefig() 在 show() 之前调用,否则图形已被清空。
import matplotlib
# list available backends
print(matplotlib.rcsetup.all_backends)
# force a backend (do this BEFORE importing pyplot)
# matplotlib.use("Agg") # non-interactive, for saving files
# matplotlib.use("TkAgg") # interactive Tk window
import matplotlib.pyplot as plt
plt.plot([1, 2, 3])
# plt.show() blocks until the window is closed
plt.savefig("out.png") # saving works without any GUI backend折线图 (plot)
基础折线图
plt.plot(x, y) 是最基础的绘图命令——用直线段连接 (x, y) 点。如果只传入一个数组,它被视为 y 值,x 默认为 0..N-1 的整数索引。plot 返回 Line2D 对象列表,你可以用它们在之后修改属性(如 line.set_color())。ax.plot() 在面向对象接口中做同样的事。
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.5)
y = x * 2
plt.plot(x, y)
plt.title("y = 2x")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()