在MATLAB中控制颜色条比例

问题描述 投票:0回答:1

问题:如何在自定义MATLAB颜色条中指定颜色过渡? 具体来说,我想让黄色(见下文)覆盖色条的更多区域(可能[19.5-21.5]或接近那个)。

使用this answer,我能够在MATLAB中创建自定义颜色条。我试图理解this answer,因为它可能是相关的。

我尝试过this answer的方法并回顾了this answerthis one并且无法实现我的目标。

Example plot w/ current colorbar and illustration of desired colorbar

完整的代表性示例如下(MATLAB R2017a)

% Data
X = [22.6 22.8 22.6 20.45 22.3 18.15 19.95 20.8]';
Y = [84 89 63 81 68 83 77 52]';
Z = [23.0 22.695 21.1450 21.5 22.09 20.5 22.075 20.915]';

% Create custom colormap  
% Reference: https://stackoverflow.com/questions/24488378/how-to-map-a-specific-value-into-rgb-color-code-in-matlab/24488819#24488819
col3 = [0 1 0]; %G
col2 = [1 1 0]; %Y
col1 = [1 0 0]; %R
n1 = 20; n2 = 20;
cmap=[linspace(col1(1),col2(1),n1);linspace(col1(2),col2(2),n1);linspace(col1(3),col2(3),n1)];
cmap(:,end+1:end+n2)=[linspace(col2(1),col3(1),n2);linspace(col2(2),col3(2),n2);linspace(col2(3),col3(3),n2)];
cmap = cmap';

% Plot
colormap(cmap), hold on, box on
p = scatter(X,Y,[],Z,'filled','DisplayName','Data3');
cb = colorbar;
cb.Limits = [18 23];
cb.Ticks = [18:1:23];

% Cosmetics
p.MarkerEdgeColor = 'k';
xlabel('X')
ylabel('Y')
cb.Label.String = 'Z';
matlab plot matlab-figure scatter-plot colorbar
1个回答
2
投票

我认为你所缺少的是调用caxis来指定将颜色范围映射到的最小值和最大值:

caxis([18 23]);

enter image description here

请注意以下行...

cb.Limits = [18 23];

...仅更改颜色条上显示的tick limits,但不会更改有关数据如何映射到颜色范围的任何信息。 caxis函数是你如何控制它(在上面的例子中,将18的值映射到一端,将值23映射到另一端)。默认情况下,您的代码将Z中的最小值和最大值映射到颜色范围(分别为20.5和23)。然后,当您将颜色条上的刻度限制设置为更大的范围时,它只会用颜色映射中的最后一种颜色填充它,在本例中为红色。这就是你看到这么多的原因。

奖金

只是因为您可能感兴趣,您还可以通过interp1函数使用插值来轻松生成颜色贴图,如下所示:

cmap = interp1([1 0 0; 1 1 0; 0 1 0], linspace(1, 3, 41));
© www.soinside.com 2019 - 2024. All rights reserved.