【问题标题】:how to specify color of contour in matlab如何在matlab中指定轮廓的颜色
【发布时间】:2016-03-06 18:43:37
【问题描述】:

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

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');

线条的颜色发生了变化,显示的级别符合预期。但是颜色条不会相应地改变。任何的想法?

【问题讨论】:

    标签: matlab matlab-figure contour


    【解决方案1】:

    默认情况下,contour 绘图使用图形的当前颜色图来决定等高线的颜色。与其创建一堆单独的 contour 对象(不再像您发现的那样与颜色图/颜色条绑定),不如构建一个与您想要的颜色相对应的自定义颜色图来使用。

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

    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])
    

    现在您的数据已按照您想要的方式着色,但现在您的数据已链接到颜色栏。

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 1970-01-01
      • 2013-03-05
      • 2012-08-29
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      相关资源
      最近更新 更多