一、子图布局
-
使用
plt.subplots
绘制均匀状态下的子图- 返回两个元素:画布 (
Figure
) 和子图对象 (Axes
),可以通过索引访问每个子图。 - 参数:
nrows
、ncols
:指定行数和列数。figsize
:指定整个画布的大小。sharex
、sharey
:是否共享横轴和纵轴刻度。tight_layout
:调整子图的相对大小,使得图形内容不重叠。
示例:
fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True) fig.suptitle('样例1', size=20) for i in range(2): for j in range(5): axs[i][j].scatter(np.random.randn(10), np.random.randn(10)) axs[i][j].set_title(f'第{i+1}行,第{j+1}列') axs[i][j].set_xlim(-5, 5) axs[i][j].set_ylim(-5, 5) if i == 1: axs[i][j].set_xlabel('横坐标') if j == 0: axs[i][j].set_ylabel('纵坐标') fig.tight_layout()
- 返回两个元素:画布 (
-
使用
subplot
(pyplot 模式)plt.subplot(nrows, ncols, index)
用于绘制子图,指定行数、列数和当前子图的位置。- 支持简写格式,如
plt.subplot(224)
等价于plt.subplot(2, 2, 4)
。
示例:
plt.subplot(2, 2, 1) plt.plot([1, 2], 'r') plt.subplot(2, 2, 2) plt.plot([1, 2], 'b') plt.subplot(224) plt.plot([1, 2], 'g')
-
极坐标图
- 通过
projection='polar'
创建极坐标图。 - 示例:绘制极坐标下的散点图。
示例:
N = 150 r = 2 * np.random.rand(N) theta = 2 * np.pi * np.random.rand(N) area = 200 * r**2 colors = theta plt.subplot(projection='polar') plt.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)
- 通过
-
使用
GridSpec
绘制非均匀子图add_gridspec()
方法可以自定义子图的宽度和高度比例。- 支持跨行或跨列的子图布局。
示例:
fig = plt.figure(figsize=(10, 4)) spec = fig.add_gridspec(nrows=2, ncols=5, width_ratios=[1,2,3,4,5], height_ratios=[1,3]) for i in range(2): for j in range(5): ax = fig.add_subplot(spec[i, j]) ax.scatter(np.random.randn(10), np.random.randn(10)) fig.tight_layout()
跨行或跨列的布局:
fig = plt.figure(figsize=(10, 4)) spec = fig.add_gridspec(nrows=2, ncols=6, width_ratios=[2,2.5,3,1,1.5,2], height_ratios=[1,2]) ax1 = fig.add_subplot(spec[0, :3]) # 跨3列 ax2 = fig.add_subplot(spec[0, 3:5]) # 跨2列 ax3 = fig.add_subplot(spec[:, 5]) # 跨所有行 fig.tight_layout()
二、子图上的方法
-
绘制直线
- 常用方法:
axhline
(水平线)、axvline
(垂直线)、axline
(任意方向的线)。
示例:
fig, ax = plt.subplots(figsize=(4, 3)) ax.axhline(0.5, 0.2, 0.8) ax.axvline(0.5, 0.2, 0.8) ax.axline([0.3, 0.3], [0.7, 0.7])
- 常用方法:
-
添加网格
- 使用
ax.grid(True)
添加网格。
示例:
fig, ax = plt.subplots(figsize=(4, 3)) ax.grid(True)
- 使用
-
坐标轴的对数坐标设置
- 使用
set_xscale
或set_yscale
设置坐标轴的对数坐标。
示例:
fig, axs = plt.subplots(1, 2, figsize=(10, 4)) for j in range(2): axs[j].plot(list('abcd'), [10**i for i in range(4)]) if j == 0: axs[j].set_yscale('log') fig.tight_layout()
- 使用