Reputation: 23
So if I run my code I am supposed to get a legend for both the plots but I am getting only for one. Can someone please give a solution. I want both plots in one graph but the separate legend command is not working. The code is as follow:
close all;clear all;clc
load stiffhless
figure
plot(FI*180/pi,ktot);
xlabel('\psi [deg]');ylabel('k');
title('Stiffness coeff. of flapping motion eq.')
xlim([0,360])
set(gca,'XTick',0:45:360)
grid on
legendCell=strcat('\mu=',strtrim(cellstr(num2str(mu_vect'))));
legend(legendCell)
hold on
load stiffarti
plot(FI*180/pi,ktot,'--');
xlabel('\psi [deg]');ylabel('k');
title('Stiffness coeff. of flapping motion eq.')
xlim([0,360])
set(gca,'XTick',0:45:360)
grid on
legendCell=strcat('\mu=',strtrim(cellstr(num2str(mu_vect'))));
legend(legendCell)
Upvotes: 0
Views: 386
Reputation: 1222
Per @dfri's comments, it's easiest for us to help you if you can produce a minimal, complete and verifiable example of the problem you're having (in doing so, you may even solve the problem yourself!).
Carefully reading relevant MATLAB documentation (legend) is also a great place to start when seemingly innocent commands aren't behaving the way you expect them to.
Those comments aside, here are two possible ways to include multiple legend entries:
If you want to add all legend entries at once, I believe this is a minimal version of your problem:
x=1:10; y=rand(1,10);
figure; plot(x,y);
legendCell='foo';
legend(legendCell);
hold on;
plot(x,-y);
legendCell='bar';
legend(legendCell);
If so, the second call to legend
is overwriting the first call. In this case, @dfri's comment is exactly right -- this is what you mean to do:
figure; plot(x,y);
legendCell1='foo';
hold on;
plot(x,-y);
legendCell2='bar';
legend(legendCell1,legendCell2);
Or even better, no need for the legendCell1/2
variables:
legend('foo','bar');
If you need to add legend entries one at a time, here's one method to do so:
figure; plot(x,y);
L=legend('foo');
hold on;
plot(x,-y);
L=legend(L.String,'bar');
plot(x,2*y);
L=legend(L.String,'boo');
plot(x,-2*y);
L=legend(L.String,'far');
...
Assigning a variable name L
to the legend object allows you to get a list of all existing legend strings L.String
. So, by calling L=legend(...)
again, you can essentially add elements to the existing list.
Upvotes: 1