【问题标题】:How do I modify the legend in a Matlab plot?如何修改 Matlab 图中的图例?
【发布时间】:2014-09-19 11:49:55
【问题描述】:

我想画四个圆,两种颜色。我正在使用圆形功能来绘制一个圆圈。我遇到了legend() 的问题。它将两个数据用相同的颜色着色。

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

下图显示了问题。两种颜色都是蓝色,其中一个是红色。

有什么建议吗?

【问题讨论】:

    标签: matlab plot legend


    【解决方案1】:

    您可以使您的函数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
    

    结果如下:

    【讨论】:

    • 谢谢。这是一个很好的解决方案。
    【解决方案2】:

    问题是你画了 4 个东西,而图例中只有 2 个条目。 因此,它将选择前四件事的颜色来为图例着色。

    现在没有机会亲自尝试,但我想最简单的“解决方案”是先画第三个圆圈,然后再画第二个圆圈。

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

    【讨论】:

    • 谢谢@Dennis。它解决了这个问题。但是我有更多的圆圈,所以我需要将它们作为每种颜色的一组。这个问题还有其他解决方案吗?或者有没有其他不使用图例的方法来绘制这个框,以便我可以随意修改它?
    • @CroCo 这个回答有点模糊,不过如果你只是想设置图例的颜色,或许可以看看这个:stackoverflow.com/questions/10957541/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2017-06-19
    相关资源
    最近更新 更多