Combine legends of two plots (Two plots are in a for loop)

조회 수: 8 (최근 30일)
Karthik Brs
Karthik Brs 2015년 11월 4일
댓글: Karthik Brs 2015년 11월 4일
Hello everyone, I have a small problem here. I am suppose to combine two legends from two plots which are in a 'for' loop. Whenever I try to combine two legends, only one gets printed or I get a error! In other words, I just to add the legend with the name 'TOTAL' to the legend of the first plot! I am enclosing my code and variables with this query if you like to give it a try. Thank you in advance!
for y1=1:1:ordn
while feof(fid) == 0
tline = fgetl(fid);
n1=n1+1;
if n1 == line(y1) + 4
c = strsplit(tline,',');
ord(y1).dat = fscanf(fid, ' %f, %f, %f, %f, %f, %f', [6, diffr(y1)]);
ord(y1).freq = transpose(ord(y1).dat(1,:));
ord(y1).rpm = ord(y1).freq/ord1(y1)*60;
RPM{y1} = ord(y1).rpm;
ord(y1).total_lw = transpose(ord(y1).dat(2,:));
ord(y1).lw = transpose(ord(y1).dat(3,:));
ord(y1).lw2 = transpose(ord(y1).dat(4,:));
ord(y1).lw3 = transpose(ord(y1).dat(5,:));
ord(y1).lw4 = transpose(ord(y1).dat(6,:));
x = ord(y1).freq; r = ord(y1).rpm; f = ord(y1).freq;
z1 = ord(y1).lw; z2 = ord(y1).lw2; z3 = ord(y1).lw3;
z5 = ord(y1).total_lw; z4 = ord(y1).lw4;
figure(20);
plot(r,z5,'color',C{y1},'Linewidth',2);
hold on
title(sprintf('%s for the Total Time Orders',Method),'FontSize',16,'Fontweight','bold');
grid on;
xlabel('RPM','FontSize',12,'Fontweight','bold');
ylabel('Schallleistung dB','FontSize',12,'Fontweight','bold');
legendInfo{y1} = ['Total Time order ' num2str(ord1(y1))];
li = legend(legendInfo,'location','southeast');
end
for s=1:1:length(tempLw)
div{s} = tempLw{1,s}./10;
raise10{s} = 10.^div{s};
LwSum = LwSum + raise10{1,s};
LwlogSum = 10*log10(LwSum);
end
p1 = plot(a1,LwlogSum,'k','Linewidth',1.5);
ki = legend('TOTAL','location','northeast');
%legend(li,ki);
hold off;

채택된 답변

Thorsten
Thorsten 2015년 11월 4일
You cannot "add" an entry to an existing legend, as far as I know. But you can create handles for you plots and concatenate the handles to create a handle for the legend that contains all plots:
R = rand(4);
h = plot(R)
legend(h, '1', '2', '3', '4')
hold on
h2 = plot(mean(R), 'k', 'LineWidth', 2)
legend([h; h2], '1', '2', '3', '4', 'Total')
  댓글 수: 3
Thorsten
Thorsten 2015년 11월 4일
R = rand(4);
legendtext = {'1', '2', '3', '4'};
for i = 1:size(R,1)
h(i) = plot(R(i,:));
legend(h, legendtext(1:i))
if ~ishold, hold on, end
pause
end
fulllegendtext = legendtext;
fulllegendtext{end+1} = 'Total';
h2 = plot(mean(R), 'k', 'LineWidth', 2);
legend([h h2], fulllegendtext)
Karthik Brs
Karthik Brs 2015년 11월 4일
Awesome! Works!! Thanks a lot!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by