How to dynamically allocate labels to a legend?
138 次查看(过去 30 天)
显示 更早的评论
I want to dynamically assign a legend to a data set with a changing number of vectors (v_1, v_2,...,v_n) that I plot against a single vector A. The vectors v_n are stored in a cell array, T{1,n}.
Some psuedo-code would be something like,
n=5
for i=1:n
plot(A,T{1,i})
legend('X=',i) % Essentially I want something like, legend('X=1', 'X=2', 'X=3', 'X=4', 'X=5',..., 'X=n')
end
So in this example by setting the value of n to be 5, I should get 5 different plots on my graph with a legend that displays X=1 through to X=5.
Is there a way to do this?
Thank you!
0 个评论
采纳的回答
KSSV
2019-2-14
n=5 ;
lgd = cell(n,1) ;
figure
hold on
for i=1:n
plot(rand(10,1)) ;
lgd{i} = strcat('X=',num2str(i)) ;
end
legend(lgd)
2 个评论
更多回答(1 个)
Steven Lord
2023-6-25
Rather than generating the legend strings as a separate variable and calling legend on that variable at the end, I would set the DisplayName property of each item you want to appear in the legend then use the final legend call simply to tell MATLAB "Show the legend now."
x = 0:360;
axis([0 360 -1 1])
hold on
for k = 1:5
plot(x, sind(k*x), 'DisplayName', sprintf('sin(%d*x)', k));
end
legend show
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!