2012-10-15 36 views
6

我有下面的圖片:Matlab的 - 如何讓自定義圖例

enter image description here

,我想作一個傳奇吧。基本上,我想爲每種類型的矩形制作一個圖例。在傳說中,我想標記每條彩色線根據它標誌着體的類型:

  • 綠線:頭
  • 黃線:軀幹
  • 紫線:右手臂
  • 青色線:左臂
  • 紅線:左腿
  • 藍線:右腿

這基本上是自定義的,因爲我有更多的每種類型的矩形。我如何做一個自定義的傳說,並將其附加到繪製此圖片的圖上?

回答

2

我能想到的最簡單的方法是先繪製每種類型的一個矩形,然後爲唯一的矩形構造一個圖例。像這樣:

figure; 
hold on; 

% unique rectangles 
plot(rand(1, 10), 'b'); 
plot(rand(1, 10), 'g'); 

% the rest 
plot(rand(1, 10), 'b'); 
plot(rand(1, 10), 'g'); 

% use normal legend with only as many entries as there are unique rectangles 
legend('Blue', 'Green'); 

您將有許多相同顏色的線條,但只有唯一顏色的圖例。

7

有兩種方法可以解決這個問題。你可以創建你的方塊,然後將它們分配給一個hggroup。這樣你就不會有每種顏色的多個項目。事情是這樣的:

hold on 
for ii = 1:4 
    hb(ii) = plot(rand(1,2), rand(1,2),'color','r'); 
end 

hg = hggroup; 
set(hb,'Parent',hg) 
set(hg,'Displayname','Legs') 

legend(hg) 

或者你可以創建虛擬對象,像這樣:

hold on 
for ii = 1:4 
    hb(ii) = plot(rand(1,2), rand(1,2),'color','r'); 
end 

p = plot([],[],'r'); 

legend(p,'Legs') 

前者是多了幾分優雅。

2

我想補充到dvreed77的回答上使用hggroup對於清潔傳說的使用,我還需要設置「IconDisplayStyle」(Matlab的R2014a),使得:

%4 kinds of lines: 
n_areas = 4; 
n_lines = 10; 

%use built-in color map 
cmap = hsv(n_areas); 

%plot lines and generate handle vectors 
h_fig = figure; 
hold on 
h_lines = zeros(1,n_lines); 

for l = 1:n_areas 

    for k = 1:n_lines 
    h_lines(k) = plot(rand(1,2), rand(1,2),'Color',cmap(l,:)); 
    end 

    %Create hggroup and set 'icondistplaystyle' to on for legend 
    curPlotSet = hggroup; 
    set(h_lines,'Parent',curPlotSet); 
    set(get(get(curPlotSet,'Annotation'),'LegendInformation'),... 
     'IconDisplayStyle','on'); 
end 

%Now manually define legend label 
legend('heads','legs','hands','feet') 
+2

感謝downvote,我很確定這是一個有用的答案無論如何^。^ –

1

只是畫外的傳說點劇情:

figure; 
plot(-1,-1,'gs',-1,-1,'b^',-1,-1,'ro'); 
legend('x1','x2','x3','Location','NorthWest'); 
xlim([0,1]); ylim([0,1]);