How to dynamically allocate labels to a legend?
Show older comments
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!
Accepted Answer
More Answers (1)
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
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!