2016-03-06 294 views
0

我認爲這不是一個新鮮的問題,但我沒有找到一個具體的解決方案,或者我找到的解決方案迄今沒有解決我的問題。我試圖繪製matlab中某些3D數據的特定級別的輪廓(不是contourf)。我發現一些解決方案試圖尋找補丁對象並從那裏爲每條輪廓線定義面部顏色。如何在matlab中指定輪廓的顏色

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

默認情況下,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]) 

enter image description here

現在你有數據有色,你所希望的方式,但現在你的數據鏈接到彩條。