Map values to colors in Matplotlib


To map values to a colors tuple(red, green and blue) in matplotlib, we can take the following steps −

  • Create a list of values from 1.00 to 2.00, count=10.

  • Get linearly normalized data into the vmin and vmax interval.

  • Get an object to map the scalar data to rgba.

  • Iterate the values to map the color values.

  • Print the values against the mapped red, green, and blue values.

Example

import numpy as np
from matplotlib import cm, colors
values = np.linspace(1.0, 2.0, 10)
norm = colors.Normalize(vmin=1.0, vmax=2.0, clip=True)
mapper = cm.ScalarMappable(norm=norm, cmap=cm.Greys_r)
for value in values:
   print("%.2f" % value, "=",
      "red:%.2f" % mapper.to_rgba(value)[0],
      "green:%.2f" % mapper.to_rgba(value)[1],
      "blue:%.2f" % mapper.to_rgba(value)[2])

Output

1.00 = red:0.00 green:0.00 blue:0.00
1.11 = red:0.13 green:0.13 blue:0.13
1.22 = red:0.28 green:0.28 blue:0.28
1.33 = red:0.41 green:0.41 blue:0.41
1.44 = red:0.53 green:0.53 blue:0.53
1.56 = red:0.66 green:0.66 blue:0.66
1.67 = red:0.78 green:0.78 blue:0.78
1.78 = red:0.87 green:0.87 blue:0.87
1.89 = red:0.95 green:0.95 blue:0.95
2.00 = red:1.00 green:1.00 blue:1.00

Updated on: 01-Jun-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements