使用 Matplotlib 以图例样式绘制离散颜色条

Plotting discrete colorbar in legend style using Matplotlib

有时,我想以 pcolormesh 样式绘制离散值。

例如,表示一个包含 int 0~7 的 100x100 形状的二维数组

data  = np.random.randint(8, size=(100,100))
cmap = plt.cm.get_cmap('PiYG', 8) 
plt.pcolormesh(data,cmap = cmap,alpha = 0.75)
plt.colorbar()  

如图所示:

如何生成图例样式的颜色条。换句话说,每个颜色框对应于它的值(例如粉色颜色框 --> 0)

这里有一个插图(不适合这个例子):

也许最简单的方法是创建相应数量的 Patch 实例:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np

data  = np.random.randint(8, size=(100,100))
cmap = plt.cm.get_cmap('PiYG', 8) 
plt.pcolormesh(data,cmap = cmap,alpha = 0.75)
# Set borders in the interval [0, 1]
bound = np.linspace(0, 1, 9)
# Preparing borders for the legend
bound_prep = np.round(bound * 7, 2)
# Creating 8 Patch instances
plt.legend([mpatches.Patch(color=cmap(b)) for b in bound[:-1]],
           ['{} - {}'.format(bound_prep[i], bound_prep[i+1] - 0.01) for i in range(8)])