make a legend display a variable input
7 次查看(过去 30 天)
显示 更早的评论
I'm trying to add a legend in a figure where the input of the legend is variable. I want a plot which displays 4-6 conditions with a legend that displays the corresponding conditions.
The code below is only to illustrate what i want to create. The first for-loop(for plotting) is of no importance.
clc
close all
clearvars
tst = [ 12 21 14 18];
ntst = numel(tst);
for w=1:ntst
hold on
x=linspace(1,100);
y=sin(x+x*tst(w));
plot(x,y,'Color',[rand(1),rand(1),rand(1)])
end
b='';
for a=1:ntst
b=[num2str(tst(a)),' test'];
end
legend(b,'Location', 'southeast')
The actual function has a matrix that contains data for 4-6 conditions and there is no need to plot it in a loop. The text that i want to display in the legend is formatted the same as 'tst' in the code above.
0 个评论
回答(1 个)
Jos (10584)
2016-7-6
编辑:Jos (10584)
2016-7-6
% an example
x = -10:10 ;
color = {'r','g','b','k'} ;
hold on ;
for k=1:4,
y = (k-2) * x + k ;
ph(k) = plot(x,y,'.-') ;
set(ph(k),'color',color{k}) ;
legendstr{k} = sprintf('%d * x + %d',[k-2 k]) ;
end
hold off
legend(ph,legendstr)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!