-1

I am trying to recreate the colorbar shown below in matplotlib

enter image description here

The different colors are given below in RGB format

[[255, 255, 255],
 [160, 160, 160],
 [133, 231, 137],
 [105, 191, 104],
 [207, 216, 255],
 [0, 0, 199],
 [255, 255, 0],
 [205, 0, 0]]

Where each color is the beginning and end of the obvious gradient...so the "white to gray" part of the colormap goes from [255,255,255] to [160,160,160]

For convenience, lets say the gray portion of the colorbar goes from 0 to 0.2, the green from 0.2 to 0.333 (1/3), the blue from 1/3 to 2/3, and the yellow-red from 2/3 to 1.

Thanks!

hm8
  • 1,381
  • 3
  • 21
  • 41
  • Is this what you are looking for? https://stackoverflow.com/a/16836182/190597 – unutbu Mar 29 '18 at 16:48
  • See also: http://scipy.github.io/old-wiki/pages/Cookbook/Matplotlib/ColormapTransformations – unutbu Mar 29 '18 at 16:49
  • Or perhaps https://stackoverflow.com/a/14779462/190597 – unutbu Mar 29 '18 at 16:50
  • The uneven spacing of the colors (grey and green don't occupy the same potion of the colormap as the other colors), and the discrete jump between colors is what is tripping me up and making those example maybe not entirely applicable. – hm8 Mar 29 '18 at 16:54

1 Answers1

1

The easiest way to create a colormap is matplotlib.colors.LinearSegmentedColormap.from_list(). You can not only provide a list of colors but also a list of (value, color) tuples, as to account for the different color spacings.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

colors = [[255, 255, 255],
          [160, 160, 160],
          [133, 231, 137],
          [105, 191, 104],
          [207, 216, 255],
          [0, 0, 199],
          [255, 255, 0],
          [205, 0, 0]]
colors = np.array(colors)/255.

bins = [0,0.2,.2,.333,.333,.666,.666,1]
color_list = list(zip(bins,colors))

cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", color_list)

a = np.linspace(0,1)
plt.imshow(np.atleast_2d(a), cmap=cmap)

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712