6

I am trying to create a colormap that is a gradient from dark red to a very light green/white. I'll attach an example of the output as a screenshot below.

enter image description here

I've had a play around with the following code:

from matplotlib import pyplot as plt
import matplotlib 
import numpy as np

plt.figure()
a=np.outer(np.arange(0,1,0.01),np.ones(100))
cdict2 = {'red':   [(0.0,  0.1, 0.2),
                   (0.3,  0.4, 0.5),
                   (0.5,  0.5, 0.5),
                   (1.0,  1.0, 1.0)],
         'green': [(0.0,  0.0, 0.0),
                  (0.5, 0.5, 0.5),
                  (0.75, 1.0, 1.0),
                  (1.0,  1.0, 1.0)],
         'blue':  [(0.0,  0.0, 0.0),
                  (0.0,  0.0, 0.0),
                  (1.0,  1.0, 1.0)]} 
my_cmap2 = matplotlib.colors.LinearSegmentedColormap('my_colormap2',cdict2,256)
plt.imshow(a,aspect='auto', cmap =my_cmap2)                   
plt.show()

But I can't get it to replicate the attached colormap. I'm also not sure if there could be a more effective way to achieve this?

Current Output: I've manipulated the values to try and get the gradient to replicate the attached colormap. But I can't get the red-orange-yellow-green gradient correct

enter image description here

3 Answers3

5

From this other answer:

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

def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
    new_cmap = colors.LinearSegmentedColormap.from_list(
        'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
        cmap(np.linspace(minval, maxval, n)))
    return new_cmap

arr = np.linspace(0, 50, 100).reshape((10, 10))
fig, ax = plt.subplots(ncols = 2)

new_cmap1 = truncate_colormap(plt.get_cmap('jet'), 0.45, 1.0)
new_cmap2 = truncate_colormap(plt.get_cmap('brg'), 1.0, 0.45)

ax[0].imshow(a,aspect='auto', cmap = new_cmap1)
ax[1].imshow(a,aspect='auto', cmap = new_cmap2)
plt.show()

enter image description here

caverac
  • 1,505
  • 2
  • 12
  • 17
  • Sorry. I'm being fickle with it but that transition to a very light green, even white. I might need another method sorry –  Dec 13 '18 at 02:58
5

Since you're trying to emulate an existing gradient rather than creating one from arbitrary colors, it simply becomes a matter of finding a formula that matches the measured gradient values.

Start by taking the average pixel r,g,b values at every point on the gradient. You need to get a pure image first, the one you posted has a white border and some ringing on the edges; I used an image editor to clean that up.

Once you have measured values, you can use numpy.polyfit to do a curve fit. I took a wild guess that 5 degrees would be enough for a good fit, yielding an array of 6 coefficients. Here you can see a plot of the measured values with the fitted curve overlaid. A pretty good match I'd say.

R,G,B measured values and curve fit

And here's code to recreate the gradient using those curves.

rp = [-1029.86559098,  2344.5778132 , -1033.38786418,  -487.3693808 ,
         298.50245209,   167.25393272]
gp = [  551.32444915, -1098.30287507,   320.71732031,   258.50778539,
         193.11772901,    30.32958789]
bp = [  222.95535971, -1693.48546233,  2455.80348727,  -726.44075478,
         -69.61151887,    67.591787  ]

def clamp(n):
    return min(255, max(0, n))

def gradient(x, rfactors, gfactors, bfactors):
    '''
    Return the r,g,b values along the predefined gradient for
    x in the range [0.0, 1.0].
    '''
    n = len(rfactors)
    r = clamp(int(sum(rfactors[i] * (x**(n-1-i)) for i in range(n))))
    g = clamp(int(sum(gfactors[i] * (x**(n-1-i)) for i in range(n))))
    b = clamp(int(sum(bfactors[i] * (x**(n-1-i)) for i in range(n))))
    return r, g, b

from PIL import Image
im = Image.new('RGB', (742, 30))
ld = im.load()
for x in range(742):
    fx = x / (742 - 1)
    for y in range(30):
        ld[x,y] = gradient(fx, rp, gp, bp)

new gradient

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
2

You can load the image you already have and create a colormap from it. Unfortunately, the image has white borders - those need to be cut first.

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

cim = plt.imread("https://i.stack.imgur.com/4q2Ev.png")
cim = cim[cim.shape[0]//2, 8:740, :]

cmap = mcolors.ListedColormap(cim)


data = np.random.rand(10,10)
plt.imshow(data, cmap=cmap)
plt.colorbar()
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712