Why does legend highlight the wrong colors with lineplot?

1 次查看(过去 30 天)
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)

更多回答(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