legend showing wrong colours

조회 수: 11 (최근 30일)
Robin Strak
Robin Strak 2020년 3월 17일
댓글: Adam Danz 2020년 3월 18일
Hi,
I want to plot 4 different arrays and their corresponding trendlines. In order to discriminate between those 4 I want them to have their own colour. Unfortunately my legend doesn´t correspond to the plots (see attached screenshot) - it should only show "Graph A1", "Graph A2", "Graph A3" and Graph A4" with four different colours.
j = 1;
k = 1;
str = {'A1', 'A2', 'A3', 'A4'};
col = {'r', 'k', 'g', 'b'};
for i = 1:20:80
plot(M_3(i:19+i), col{k}, 'LineWidth',1);
str = [str ("Graph " + str(j))];
c_rms = polyfit(time,M_3(i:19+i),1);
y_est = polyval(c_rms,time);
hold on
plot(time,y_est, col{k}, 'LineWidth',2);
j = j+1;
k = k+1;
end
set(gcf,'position',[0 500 1000 300])
xlabel('time / min');
ylabel('electrical activity in % of the maximal force');
grid on; grid minor;
legend(str);
I would be very happy if you could help me out, maybe I just missordered the loop.
Thanks,
Robin

채택된 답변

Adam Danz
Adam Danz 2020년 3월 17일
편집: Adam Danz 2020년 3월 17일
The easiest way to manage legend text is by using the DisplayName property of graphics objects. Here's how that might look when plotting in a loop.
str = {'A1', 'A2', 'A3', 'A4'};
hold on
for i = 1:4
% . . . skipping stuff
plot(x,y,'DisplayName', str{i})
plot(xFit,yFit,'DisplayName', [str{i},' fit'])
end
legend()
If you only want some objects to appear in the legend,
str = {'A1', 'A2', 'A3', 'A4'};
hold on
handles = gobjects(4,1);
for i = 1:4
% . . . skipping stuff
handles(i) = plot(x,y,'DisplayName', str{i});
plot(xFit,yFit)
end
legend(handles)
  댓글 수: 2
Robin Strak
Robin Strak 2020년 3월 18일
Thanks for you quick answer, Adam!
I tried to incorporate your tip, but in my case there still a little bug:
As I want to plot M_3 in 4 parts I looped it with for j = 1:20:80, so in order to choose the displayed string (A1,A2, ...) I need another loop - as you descriped.
time = linspace(0,22,20);
str = {'A1', 'A2', 'A3', 'A4'};
hold on
for i = 1:4
for j = 1:20:80
plot(time, M_3(i:19+i),'DisplayName', str{i})
j = j+1;
end
end
legend()
I´ve tried that but now I´ve got 16 graphs plotted. Do you think I could solve it with only one loop?
Thanks,
Robin
Adam Danz
Adam Danz 2020년 3월 18일
Instead of setting up your loop like this
for i = 1:20:80
plot(M_3(i:19+i), . . .);
. . .
end
set it up like this
vec = 1:20:80;
for i = 1:numel(vec)
plot(M_3(vec(i):19+vec(i)), . . .);
% ^^^^^^ ^^^^^^
. . .
end
That way your loop uses integer values 1:n that can be used as indices.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by