How to create an interpolated colormap or color palette from two colors?

18.2k views Asked by At

I'd like to create a color palette between two colors. For instance between Blue and Red with 20 or 50 instances.

How can this be achieved in Matlab R2014b?

1

There are 1 answers

5
Robert Seifert On BEST ANSWER

You can use any kind of interpolation (e.g. interp1) to create your own custom colormap between two colors or multiple colors. A colormap is basically a 3-column matrix with RGB-values. In your case its pretty simple, as you just need red with [1 0 0] and blue [0 0 1] and linearly interpolated in between. linspace is therefore the best choice.

n = 50;               %// number of colors

R = linspace(1,0,n);  %// Red from 1 to 0
B = linspace(0,1,n);  %// Blue from 0 to 1
G = zeros(size(R));   %// Green all zero

colormap( [R(:), G(:), B(:)] );  %// create colormap

%// some example figure
figure(1)
surf(peaks)
colorbar

enter image description here

Note that you could also use the the colormap GUI by typing colormapeditor.


Alternative you can also use 2D-interpolation:

n = 50;                %// number of colors

cmap(1,:) = [1 0 0];   %// color first row - red
cmap(2,:) = [0 1 0];   %// color 25th row - green
cmap(3,:) = [0 0 1];   %// color 50th row - blue

[X,Y] = meshgrid([1:3],[1:50]);  %// mesh of indices

cmap = interp2(X([1,25,50],:),Y([1,25,50],:),cmap,X,Y); %// interpolate colormap
colormap(cmap) %// set color map

%// some example figure
figure(1)
surf(peaks)
colorbar

enter image description here


And just another example using spline-interpolation to get wider areas of blue and red:

n = 50;                %// number of colors

v = [0,0,0.1,0.5,0.9,1,1];
x = [-5*n,0, 0.45*n, 0.5*n, 0.55*n, n, 5*n]; 
xq = linspace(1,n,n);
vq = interp1(x,v,xq,'spline');
vq = vq - min(vq);
vq = vq./max(vq);

B = vq;  %// Blue from 0 to 1 with spline shape
R = fliplr(B);  %// Red as Blue but mirrored
G = zeros(size(R));   %// Green all zero

colormap( [R(:), G(:), B(:)] );  %// create colormap

%// some example figure
figure(1)
surf(peaks)
colorbar

enter image description here


Or use any mathematical function you want:

n = 50;                %// number of colors

t = linspace(0,4*pi,50);

B = sin(t)*0.5 + 0.5;  %// Blue from 0 to 1 as sine
R = cos(t)*0.5 + 0.5;  %// Red from 0 to 1 as cosine
G = zeros(size(R));   %// Green all zero

colormap( [R(:), G(:), B(:)] );  %// create colormap

%// some example figure
figure(1)
surf(peaks)
colorbar

enter image description here