0

我正在尝试创建一个完全自定义的图例(即我不想使用plt.legendplt.colorbar。基于颜色图,我希望能够在颜色图中的不同点获得颜色。

gradient2n = LinearSegmentedColormap.from_list('gradient2n', ["white", "red"])
breaks = [0, 0.25, 0.5, 0.75, 1.0]
# something like this
print plt.colors_at_breaks(gradient2n, breaks)
["white", "light pink", "pink", "light red", "red"] #(or the hex/rgb equivalent)
4

1 回答 1

2

Once you've created a Colormap instance, all you need to do is call it with a float value between 0 and 1, and it will return a tuple containing the corresponding RGBA values:

>>> gradient2n(0.5)
(1.0, 0.49803921568627452, 0.49803921568627452, 1.0)

There's no straightforward way of representing arbitrary colors as 'human-readable' names - to represent 8bit color you would need 16,777,216 distinct names! However, you can easily convert the RGBA values to a hex string using matplotlib.colors.rgb2hex.

So your overall function might look like:

from matplotlib.colors import rgb2hex

def colors_at_breaks(cmap, breaks):
    return [rgb2hex(cmap(bb)) for bb in breaks]

For example:

>>> colors_at_breaks(gradient2n, breaks)
['#ffffff', '#ffbfbf', '#ff7f7f', '#ff3f3f', '#ff0000']
于 2013-10-11T16:55:43.380 回答