2014-09-19 387 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