Clear Filters
Clear Filters

Legend for selective plot

1 view (last 30 days)
klb
klb on 26 Apr 2023
Commented: klb on 27 Apr 2023
Hello everyone,
I want legend to automatically update based on what was selcted to plot. I want only vectors that are plotted to be indicated within the legend. How do i do that help!
%first column is the counter ID number, and remaining vector are values the counter counted.
my_mat = [11 2 4 5 6;
14 4 5 6 7;
25 2 3 4 5;
56 0 9 8 6]
my_mat = 4×5
11 2 4 5 6 14 4 5 6 7 25 2 3 4 5 56 0 9 8 6
counts = size(my_mat,1);
% Plot only if the the counter ID is amongst the values specified in the if-elseif-else criterion.
for u = 1: size(my_mat,1)
d = my_mat(u);
hold on
if d == 11
plot(1:counts, my_mat(u, 2:end),"LineWidth",1,"Color",'r', "LineStyle","-")
elseif d == 14
plot(1:counts, my_mat(u, 2:end),"LineWidth",1,"Color",'r', "LineStyle","--")
elseif d == 34 % not an error. Counter 25 not in criteria, therefore wont be plotted
plot(1:counts, my_mat(u, 2:end),"LineWidth",1,"Color",'b', "LineStyle","-")
elseif d == 56
plot(1:counts, my_mat(u, 2:end),"LineWidth",1,"Color",'b', "LineStyle","--")
end
end
legend('11','14','60','56', "Location","southeast") % As seen , the legend is not 'linked' to what is actually plotted. Its hardwired therefore errorprone as shown. I want only vectors that are actually plotted to be indicated within the legend. help!
Warning: Ignoring extra legend entries.
Thank you for your time.

Accepted Answer

Cris LaPierre
Cris LaPierre on 26 Apr 2023
%first column is the counter ID number, and remaining vector are values the counter counted.
my_mat = [11 2 4 5 6;
14 4 5 6 7;
25 2 3 4 5;
56 0 9 8 6];
counts = size(my_mat,1);
% Plot only if the the counter ID is amongst the values specified in the if-elseif-else criterion.
for u = 1: size(my_mat,1)
d = my_mat(u);
hold on
if d == 11
plot(1:counts, my_mat(u, 2:end),"LineWidth",1,"Color",'r', "LineStyle","-",'DisplayName','11')
elseif d == 14
plot(1:counts, my_mat(u, 2:end),"LineWidth",1,"Color",'r', "LineStyle","--",'DisplayName','14')
elseif d == 34 % not an error. Counter 25 not in criteria, therefore wont be plotted
plot(1:counts, my_mat(u, 2:end),"LineWidth",1,"Color",'b', "LineStyle","-",'DisplayName','34')
elseif d == 56
plot(1:counts, my_mat(u, 2:end),"LineWidth",1,"Color",'b', "LineStyle","--",'DisplayName','56')
end
end
legend("Location","southeast")

More Answers (0)

Community Treasure Hunt

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

Start Hunting!