0

I am trying to create a color gradient rectangle with custom annotation in Python with matplotlib. The below is the function which assigns colors based on values. I am trying to create a label for reference ( A rectangle with scores shown for colors). I am looking for something like this: https://stackoverflow.com/a/25679063/7733184 for my colors but also with range indicated as per my function.

def returncolor(value,colors):
    if value < 0.55:
        return '#B03A2E' #darkest red
    if value < 0.60:
        return '#EC7063' # light red
    if value < 0.65:
        return '#FCF3CF' # lighest yellow
    if value < 0.70:
        return '#F1C40F' # yellow
    if value < 0.75:
        return '#F39C12' # Orange
    if value < 0.80:
        return '#82E0AA'#light green
    if value < 0.85:
        return '#28B463'#dark green
    if value < 0.90:
        return '#7FB3D5'#light blue
    if value < 0.95:
        return '#2980B9'#dark blue
    if value < 1:
        return '#5B2C6F'#dark blue

A mockup of what I am trying to do is below:

enter image description here

dhanush-ai1990
  • 325
  • 4
  • 20

1 Answers1

1

As per the answer to this question, you can define a custom colormap using a ListedColormap object.

colors = ['#B03A2E','#EC7063','#FCF3CF','#F1C40F','#F39C12','#82E0AA','#28B463','#7FB3D5','#2980B9','#5B2C6F']
bounds = [0.5,0.55,0.60,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1]
cmap = matplotlib.colors.ListedColormap(colors)
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)

zvals = np.random.rand(100, 100) * 10

# tell imshow about color map so that only set colors are used
img = plt.imshow(zvals, cmap=cmap, norm=norm)

# make a color bar
plt.colorbar(img, cmap=cmap, norm=norm, boundaries=bounds, ticks=bounds)

plt.show()

enter image description here

see also the example from matplotlib's documentation.

Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75