Matplotlib - 选择与“colorbar”中的一个值相关联的一种颜色

时间:2013-03-05 22:46:36

标签: python matplotlib colorbar

我想绘制与某些值(X_i)相关联的矩形。每个矩形都将具有填充颜色,具体取决于其值X_i

是否可以使用一个colorbar并知道哪个颜色与一个值相关联?

1 个答案:

答案 0 :(得分:9)

from matplotlib.pylab import *
import matplotlib.cm as cm
import matplotlib.patches as patches

min_val = 0
max_val = 50

my_cmap = cm.get_cmap('jet') # or any other one
norm = matplotlib.colors.Normalize(min_val, max_val) # the color maps work for [0, 1]

x_i = 15
color_i = my_cmap(norm(x_i)) # returns an rgba value

rect = patches.Rectangle((.5, .5), .25, .25, color=color_i) # make your rectangle

cmmapable = cm.ScalarMappable(norm, my_cmap)
cmmapable.set_array(range(min_val, max_val))

figure()
ax = gca()
ax.add_patch(rect)
colorbar(cmmapable)
show()

还会在图表上显示一个颜色条。