How to use legend command

Hello all
I am having the data lets say for seven elements and I am ploting it using a loop in a single figure. But in these seven elements someof the elements contain nothing and then the plot for that is not plotted. Now how I can use the legend command only for the elements that are plotted?
Please guide!!!
Regards

 Accepted Answer

Is the loop still telling the figure to plot even if there isn't any data recorded? You have a few ways around it:
The first one basically tells the legend to put an "empty" headline for the second item (if nothing was plotted)
legend('item1', '', 'item3')
You can also only tell MATLAB to plot only when there is data with
if isempty(your_matrix)~=1
plot(x,y)
end
There are also other ways which you can tell the legend to ignore some entries. You can also enter the plot tools (in the top menu of figure) and do it without code.

4 Comments

Hello thanks for replying.I am adding a code to givethe clear picture.
for p=0:count_ports-1
if (SRE(:,p+1)&SPDP(:,p+1)&SYfit(:,p+1))==0
continue
else
plot(SRE(:,p+1),SPDP(:,p+1),'*',SRE(:,p+1),SYfit(:,p+1));
hold on
end
end
%x-Axis:
xlabel('Reynolds Number');
%y-Axis:
ylabel('Pressure (Pa)');
filename= sprintf('Plot_of_element%d',el);
hold off
saveas(gcf,filename,'jpg');
where SRE,SPDP,SYfit are the matrices.
I hope withthis youcanguide me better.
Regards
Mahdi
Mahdi on 27 May 2014
Edited: Mahdi on 27 May 2014
Wouldn't just adding
legend('item1', 'item2', 'item3')
in your case after the loop solve the problem? If I'm understanding it correctly, I would also change the if statement to be | (or) statements instead of and statements:
if SRE(:,p+1)==0|SPDP(:,p+1)==0|SYfit(:,p+1))==0
Hi...thanks,it should be OR...can you tell me how i can form the loop for legend as ´there will be a lot of data and thus I want a generalization such as sprintf('Element%',p). but I amnot able to generate a loop that work with legend. Please Guide I am a newbie to matlab.
Regards
Do you mean that you want the legend to be labelled differently based on the loop?
You can simply do something like this: (this is just an example)
for i=1:3
figure(i)
var1=sprintf('Plot_%d', i)
% Do your plotting here
legend(var1)
end
In this case, the legend would show Plot_1, Plot_2, Plot_3

Sign in to comment.

More Answers (0)

Tags

Asked:

on 27 May 2014

Commented:

on 27 May 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!