[英]Plotting discrete colorbar in legend style using Matplotlib
Sometimes, I want to plot discrete value in pcolormesh style. 有时,我想以pcolormesh样式绘制离散值。
For example, to represent a 2-d array in the shape of 100x100 which contain int 0~7 例如,代表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()
The figure shows like this: 该图显示如下:
How to generate the colorbar in legend style. 如何以图例样式生成颜色条。 In other word, each color box corresponds to its value(eg pink colorbox --> 0) 换句话说,每个颜色框对应其值(例如,粉红色的颜色框-> 0)
An illustration here(Not fit this example): 这里有一个例子(不适合这个例子):
Maybe the easiest way is to create corresponding number of Patch instances: 也许最简单的方法是创建相应数量的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)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.