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

时间:2016-06-09 13:28:41

标签: python arrays python-2.7 matplotlib visualization

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

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

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()  

图中显示如下:
enter image description here

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

此处的插图(不适合此示例):

enter image description here

1 个答案:

答案 0 :(得分:4)

也许最简单的方法是创建相应数量的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)])

enter image description here