Legend for selective plot

1 次查看(过去 30 天)
klb
klb 2023-4-26
评论: klb 2023-4-27
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.

采纳的回答

Cris LaPierre
Cris LaPierre 2023-4-26
%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")

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