放置色块

色标表示图像数据的定量范围。放置在一个图中并不重要,因为需要为它们腾出空间。

最简单的情况是将颜色条附加到每个轴:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. fig, axs = plt.subplots(2, 2)
  4. cm = ['RdBu_r', 'viridis']
  5. for col in range(2):
  6. for row in range(2):
  7. ax = axs[row, col]
  8. pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1),
  9. cmap=cm[col])
  10. fig.colorbar(pcm, ax=ax)
  11. plt.show()

放置色块示例

第一列在两行中都具有相同类型的数据,因此可能需要通过调用 Figure.colorbar 和轴列表而不是单个轴来组合我们所做的颜色栏。

  1. fig, axs = plt.subplots(2, 2)
  2. cm = ['RdBu_r', 'viridis']
  3. for col in range(2):
  4. for row in range(2):
  5. ax = axs[row, col]
  6. pcm = ax.pcolormesh(np.random.random((20, 20)) * (col + 1),
  7. cmap=cm[col])
  8. fig.colorbar(pcm, ax=axs[:, col], shrink=0.6)
  9. plt.show()

放置色块示例2

使用此范例可以实现相对复杂的颜色条布局。请注意,此示例使用 constrained_layout = True 可以更好地工作

  1. fig, axs = plt.subplots(3, 3, constrained_layout=True)
  2. for ax in axs.flat:
  3. pcm = ax.pcolormesh(np.random.random((20, 20)))
  4. fig.colorbar(pcm, ax=axs[0, :2], shrink=0.6, location='bottom')
  5. fig.colorbar(pcm, ax=[axs[0, 2]], location='bottom')
  6. fig.colorbar(pcm, ax=axs[1:, :], location='right', shrink=0.6)
  7. fig.colorbar(pcm, ax=[axs[2, 1]], location='left')
  8. plt.show()

放置色块示例3

下载这个示例