为多张子图设置同一个色标
时间: 2023-07-14 15:12:53 浏览: 313
可以使用 matplotlib
库中的 colorbar
函数来为多张子图设置同一个色标。具体操作步骤如下:
在所有子图中要用到的数据中,找到最小值和最大值,用
vmin
和vmax
变量保存。在所有子图中使用相同的
cmap
变量,该变量定义了色标的颜色映射关系。在每个子图中都绘制图像,并在最后一个子图中使用
colorbar
函数绘制色标。
以下是一个示例代码,展示了如何为三张子图设置同一个色标:
import matplotlib.pyplot as plt
import numpy as np
# 创建数据
x = np.linspace(-np.pi, np.pi, 100)
y = np.linspace(-np.pi, np.pi, 100)
X, Y = np.meshgrid(x, y)
Z1 = np.sin(X+Y)
Z2 = np.sin(X-Y)
Z3 = np.sin(X*Y)
# 获取最小值和最大值
vmin = min(Z1.min(), Z2.min(), Z3.min())
vmax = max(Z1.max(), Z2.max(), Z3.max())
# 定义颜色映射关系
cmap = plt.cm.jet
# 绘制三个子图
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))
for i, Z in enumerate([Z1, Z2, Z3]):
im = ax[i].imshow(Z, cmap=cmap, vmin=vmin, vmax=vmax)
ax[i].set_xticks([])
ax[i].set_yticks([])
# 绘制一个色标
fig.colorbar(im, ax=ax.ravel().tolist(), shrink=0.6)
plt.show()
运行上述代码,可以看到三张子图共用一个色标的效果。
相关推荐


















