Why does legend highlight the wrong colors with lineplot?

조회 수: 1 (최근 30일)
Boris Blagov
Boris Blagov 2023년 8월 14일
댓글: Boris Blagov 2023년 8월 15일
Hey everyone,
I want to highlight specific lines in a plot and I found a weird behaviour in Matlab 2019b. If I plot them using a logical index, the legend does not color the correct lines.
Here is a Minimal Working Example:
clc
clear
n = 10;
t = 20;
tt = rand(t,n);
legstr = cellstr(string(('a':'z').').');
ind1 = ones(1,n); % all elements except 2nd and 5th
ind1(2) = 0;
ind1(5) = 0;
ind1 = logical(ind1);
ind2 = zeros(1,n); % second element only
ind2(2) = 1;
ind2 = logical(ind2);
ind3 = zeros(1,n); % 5th element only
ind3(5) = 1;
ind3 = logical(ind3);
% plot all elements except 2nd and 5th
plot(tt(:,ind1),'Color',0.6*ones(1,3))
hold on
% plot 2nd
plot(tt(:,ind2),'Color','r')
% plot 5th
plot(tt(:,ind3),'Color','b')
hold off
legend(legstr(1:n))
The above code generates a matrix called tt, which has 20 elements and 10 variables (called n). I want to plot them all but highlight the second and the fith variable. So I create an index for those, plot all except 2nd and 5th and then plot those individually, However, the legend highlights the last two, which is wrong.
If I plot all of tt (uncomment line 8 and 9) the legend is all gray.
This is a MWE, in the original code there is more going on, so I just used shortcuts to recreate the problem.

채택된 답변

Florian Bidaud
Florian Bidaud 2023년 8월 14일
편집: Florian Bidaud 2023년 8월 14일
This is because you plot these two curves in last. Legend is affected to the order of the plots, legend{1} is first plot, legend{2} is second plot, legend{3} is third plot etc.
You can either :
  • Change the order in the legend cell array: legstr = {'a' 'c' 'd' 'f' 'g' 'h' 'i' 'j' 'b' 'e'}
  • or change the order of plotting, like plotting the 1st curve, then the 2nd (highlighted), then 3rd and 4th, then 5th (highlighted), then 6th to last.
It is quite straightforward to do with the index numbers of your highlighted curves.
Something like that should work:
clear
n = 10;
t = 20;
tt = rand(t,n);
legstr = cellstr(string(('a':'z').').');
ind2 = 2;
ind3 = 5;
figure
hold on
for i = 1:ind2-1
plot(tt(:,i),'Color',0.6*ones(1,3))
end
plot(tt(:,ind2),'Color','r')
for i = ind2+1:ind3-1
plot(tt(:,i),'Color',0.6*ones(1,3))
end
plot(tt(:,ind3),'Color','b')
for i = ind3+1:n
plot(tt(:,i),'Color',0.6*ones(1,3))
end
legend(legstr)
  댓글 수: 1
Boris Blagov
Boris Blagov 2023년 8월 15일
I see. I have to see how to implement this in my code, which is more convoluted.
Thanks!

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by