Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping range of integer values to colors in python

I have integers ranging from 0 to 10000. I want to map a color to each of these. Then based on the integer value i want to retrieve RGB equivalent of the color corresponding to integer value. Basically i want to have an interpolation effect between two or more colors e.g. if the colors are green and red,then green having least weight(0) and red having having highest weight (10000). how can i implement this mapping using matplotlib or is there any other library for the same.

like image 325
Sarang Avatar asked Sep 04 '14 20:09

Sarang


1 Answers

It is indeed possible to sample 10000 colors from a given colormap:

#!/usr/bin/python3

from numpy import arange

from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.colors import LinearSegmentedColormap


# ======
## data:

N = 10000
data = arange(N +1)


# =================
## custom colormap:

# red-green colormap:
cdict = {'red':   [(0.0, 1.0, 1.0),  # red decreases
                   (1.0, 0.0, 0.0)],

         'green': [(0.0, 0.0, 0.0),  # green increases
                   (1.0, 1.0, 1.0)],

         'blue':  [(0.0, 0.0, 0.0),  # no blue at all
                   (1.0, 0.0, 0.0)]}

red_green_cm = LinearSegmentedColormap('RedGreen', cdict, N)


# ======
## plot:

colors = cm.get_cmap(red_green_cm, N)

fig = plt.figure()
ax = fig.add_subplot(111)

# each line is of its own color:
for i, x in enumerate(data):
    ax.plot(data, data*x, color=colors(i))

fig.savefig("red-green-cm.png")

Result:

enter image description here

Edit

One can also add a colorbar:

#!/usr/bin/python3

from numpy import arange

import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.colors import LinearSegmentedColormap


# ======
## data:

N = 10000
data = arange(N +1)


# =================
## custom colormap:

# red-green colormap:
cdict = {'red':   [(0.0, 1.0, 1.0),  # red decreases
                   (1.0, 0.0, 0.0)],

         'green': [(0.0, 0.0, 0.0),  # green increases
                   (1.0, 1.0, 1.0)],

         'blue':  [(0.0, 0.0, 0.0),  # no blue at all
                   (1.0, 0.0, 0.0)] }

red_green_cm = LinearSegmentedColormap('RedGreen', cdict, N)


# ======
## plot:

colors = cm.get_cmap(red_green_cm, N)

fig = plt.figure()
ax = fig.add_subplot(111)

# each line is of its own color:
for i, x in enumerate(data):
    ax.plot(data, data*x, color=colors(i))

# make space for colorbar:
fig.tight_layout(rect=[0, 0, 0.85, 1])

# adding colorbar:
ax_cb = fig.add_axes([0.85, 0.10, 0.05, 0.8])
norm = mpl.colors.Normalize(vmin=data[0], vmax=data[-1])
cb = mpl.colorbar.ColorbarBase(ax_cb, cmap=red_green_cm, norm=norm, orientation='vertical')

fig.savefig("red-green-cm.png")

enter image description here

like image 131
Adobe Avatar answered Sep 22 '22 14:09

Adobe