如何在matlab中指定轮廓颜色

时间:2016-03-06 18:43:37

标签: matlab matlab-figure contour

我认为这不是一个新问题,但我没有找到具体的解决方案,或者我找到的解决方案到目前为止还没有解决我的问题。我试图在matlab中绘制某些3D数据的特定级别的轮廓(不是contourf)。我发现一些解决方案是尝试寻找补丁对象并从那里为每个轮廓线定义面部颜色。

f=peaks(512)*10; 
[C,h] = contour(f, [-60 -30 -20 0 20 30 50 60]); 
colorbar;
Cld = get(h, 'children');
for j=1:length(Cld)
  if strcmp(get(Cld(j), 'Type'), 'patch')
    Iso = get(Cld(j), 'CData');
    if Iso==-60
      set(Cld(j), 'facecolor', [1 0 0]);
    elseif Iso==-30
      set(Cld(j), 'facecolor', [0 1 0]);
    elseif Iso==-20
      set(Cld(j), 'facecolor', [0 0 1]);
    elseif Iso==0
      set(Cld(j), 'facecolor', [0.5 0.3 0]);
    elseif Iso==20
      set(Cld(j), 'facecolor', [0.9 0 0.3]);
    elseif Iso==30
      set(Cld(j), 'facecolor', [0.8 0.7 0.1]);
    elseif Iso==50
      set(Cld(j), 'facecolor', [0.25 0.66 0.4]);
    elseif Iso==60
      set(Cld(j), 'facecolor', [0.5 0.1 0.3]);
    end
  end
end

此代码绘制的线不完全在-60 -30 -20 0 20 30 50和60的水平上,但也接近了。其次,它没有使用我指定的颜色,似乎它不包含来自该句柄的任何补丁对象。

更新:我找到了解决问题的方法

hold on; contour(f, [-60 -60], 'linewidth', 2, 'linecolor','m'); 
hold on; contour(f, [-30 -30], 'linewidth', 2, 'linecolor','c'); 
hold on; contour(f, [-20 -20], 'linewidth', 2, 'linecolor','y'); 
hold on; contour(f, [0 0], 'linewidth', 2, 'linecolor','k'); 
hold on; contour(f, [20 20], 'linewidth', 2, 'linecolor','b');
hold on; contour(f, [30 30], 'linewidth', 2, 'linecolor','g');
hold on; contour(f, [60 60], 'linewidth', 2, 'linecolor','r');

线条颜色发生变化,显示的水平与预期一致。但是,颜色条没有相应的变化。任何的想法?

1 个答案:

答案 0 :(得分:1)

默认情况下,contour绘图使用图形的当前色图来确定轮廓线的颜色。不是创建一堆单独的contour对象(不再像你发现的那样与色彩图/色条相关联),而是构建一个与你想要的颜色相对应的自定义色彩图更容易。

因此,对于您的示例,此colormap(基于您上面的数据)看起来像这样。

cmap = [1 0 1;  % magenta
        0 1 1;  % cyan
        1 1 0;  % yellow
        0 0 0;  % black
        0 0 1;  % blue
        0 1 0;  % green
        1 0 0]; % red

所以现在我们可以为您想要显示的所有关卡创建单个contour图表,只是区别于我们将图形的色彩图设置为自定义一个定义如上。

data = rand(10);
data = (data - 0.5) * 225;

contourLevels = [-60 -30 -20 0 20 30 60];

figure();
contour(data, contourLevels, 'LineWidth', 2);

% Use the custom colormap
colormap(cmap);

colorbar()
set(gca, 'clim', [-60 60])

enter image description here

现在,您可以按照自己的方式对数据进行着色,但现在您的数据已链接到颜色栏。

相关问题