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

拈花ヽ惹草 提交于 2019-12-04 14:32:57

问题


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:


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

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


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


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



来源:https://stackoverflow.com/questions/30851050/how-to-create-an-interpolated-colormap-or-color-palette-from-two-colors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!