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!