CroCo
CroCo

Reputation: 5741

How do I modify the legend in a Matlab plot?

I would like to draw four circles of two colors. I'm using circle function to draw a circle. I'm facing problem with legend(). It colors the two data with the same color.

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

The following picture shows the problem. Both colored as blue instead one of them is red.

enter image description here

Any suggestions?

Upvotes: 1

Views: 919

Answers (2)

Nras
Nras

Reputation: 4311

You can make your function circle() return the plot handles. Store the handles in a vector. In the end, you only call legend() once, after plotting all circles. The first argument in legend are then the function handles which you want to appear in the legend. Something like this:

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

The result looks like this:enter image description here

Upvotes: 3

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

The thing is that you draw 4 things and only have 2 entries in the legend. As such it will pick the color of the first four things to color the legend.

Not in the opportunity to try it myself now, but I guess that the easiest 'solution' would be to draw your third circle first and then the second one.

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

Upvotes: 1

Related Questions