2014-09-19 54 views
1

我想繪製兩種顏色的四個圓圈。我正在使用循環函數繪製一個圓。我面臨legend()的問題。它使用相同的顏色爲兩個數據着色。如何修改Matlab圖中的圖例?

function main 
clear all 
clc 

circle([ 10, 0], 3, 'b') 
circle([-10, 0], 3, 'b') 
circle([ 10, 10], 3, 'r') 
circle([-10, 10], 3, 'r') 

    % Nested function to draw a circle 
    function circle(center,radius, color) 
    axis([-20, 20, -20 20]) 
    hold on; 
    angle = 0:0.1:2*pi; 

    grid on 

    x = center(1) + radius*cos(angle); 
    y = center(2) + radius*sin(angle); 
    plot(x,y, color, 'LineWidth', 2); 
    xlabel('x-axis'); 
    ylabel('y-axis'); 
    title('Est vs Tr') 
    legend('true','estimated'); 
    end 


end 

下圖顯示了該問題。兩個顏色都是藍色,而其中一個是紅色的。

enter image description here

有什麼建議嗎?

回答

1

問題是你畫4件東西,只有2個條目在圖例中。 因此,它會選擇前四種顏色來標記圖例的顏色。

現在還沒有機會嘗試它,但我想最簡單的'解決方案'是先繪製第三個圓,然後繪製第二個圓。

circle([ 10, 0], 3, 'b') 
circle([ 10, 10], 3, 'r') 
circle([-10, 0], 3, 'b') 
circle([-10, 10], 3, 'r') 
+0

謝謝@Dennis。它解決了這個問題。但我有更多的圈子,所以我需要將它們保持爲每種顏色的組合。有沒有解決這個問題的另一種方法?或者還有另一種方法來繪製這個盒子而不使用圖例,以便我可以根據需要對其進行修改? – CroCo 2014-09-19 11:57:18

+1

@CroCo這有點太模糊不清,但也許你可以看看這個,如果你只是想設置圖例的顏色:http://stackoverflow.com/questions/10957541/setting-line-colors -in-legend-of-matlab-plot – 2014-09-19 12:01:02

3

您可以使您的功能circle()返回劇情句柄。將句柄存儲在一個向量中。最後,在繪製所有圈子後,您只需撥打legend()一次。圖例中的第一個參數就是您想要在圖例中出現的函數句柄。事情是這樣的:

function main 
% clear all % functions have their own workspace, this should always be empty anyway 
clc 
handles = NaN(1,2); 
handles(1,1) = circle([ 10, 0], 3, 'b'); % handle of a blue circle 
circle([-10, 0], 3, 'b') 
handles(1,2) = circle([ 10, 10], 3, 'r'); % handle of a red circle 
circle([-10, 10], 3, 'r') 

    % Nested function to draw a circle 
    function h = circle(center,radius, color) % now returns plot handle 
    axis([-20, 20, -20 20]) 
    hold on; 
    angle = 0:0.1:2*pi; 
    grid on 
    x = center(1) + radius*cos(angle); 
    y = center(2) + radius*sin(angle); 
    h = plot(x,y, color, 'LineWidth', 2); 
    xlabel('x-axis'); 
    ylabel('y-axis'); 
    title('Est vs Tr') 
    end 

% legend outside of the function 
legend(handles, 'true','estimated'); % legend for a blue and a red circle handle 
end 

結果看起來是這樣的:enter image description here

+0

謝謝。這是一個很好的解決方案。 – CroCo 2014-09-25 14:00:48