我想在两种颜色之间创建一个调色板。例如, Blue 和 Red 之间有20或50个实例。
如何在Matlab R2014b中实现这一目标?
答案 0 :(得分:12)
您可以使用任何类型的插值(例如interp1
)在两种颜色或多种颜色之间创建自己的自定义colormap。色图基本上是具有RGB值的3列矩阵。在您的情况下,它非常简单,因为您需要红色 [1 0 0]
和蓝色 [0 0 1]
并在其间进行线性插值。 linspace
因此是最佳选择。
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
请注意,您也可以通过键入colormapeditor
来使用colormap GUI。
另外,您也可以使用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
另一个例子是使用 spline-interpolation 来获得更广泛的蓝色和红色区域:
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
或使用您想要的任何数学函数:
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