2016-06-09 130 views
2

有時,我想繪製pcolormesh樣式的離散值。使用Matplotlib以圖例樣式繪製離散色條

例如,爲了表示在100×100的形狀的2-d陣列含有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

回答

3

也許最簡單的方法是創建修補實例的相應數量:

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

+0

感謝您的解決方案! –