How can one show variable values in legend of a plot?

조회 수: 307 (최근 30일)
alpedhuez
alpedhuez 2020년 5월 29일
댓글: PRAJWAL KUMAR A 2022년 6월 7일
For title, I see that
plot((1:10).^2)
f = 70;
c = (f-32)/1.8;
title(['Temperature is ',num2str(c),' C'])
But I do not know how to make this work in case of legend with more than two labels. Please advise.
  댓글 수: 2
alpedhuez
alpedhuez 2020년 5월 29일
편집: alpedhuez 2020년 5월 29일
legend1 = sprintf('Only Solar Generation[Integrated = %0.2f KW]', num1);
legend2 = sprintf('Whatever...%f', num2);
legend3 = sprintf('Whatever...%.1f', num3);
legend(legend1, legend2, legend3);
dpb
dpb 2020년 5월 29일
fmts = {'Only Solar Generation[Integrated = %0.2f KW]';
'Whatever...%f';
'Whatever...%.1f'};
nums=[a b c].';
legends=compose(fmts,nums);
hLg=legend(legends);
saves generating and having to use sequentially-named variables and the need to edit all of them in case something changes. This way all the edits are in one place and the number, order, etc., etc., etc., ... are all independent of the code--and vice versa.

댓글을 달려면 로그인하십시오.

채택된 답변

dpb
dpb 2020년 5월 29일
편집: dpb 2020년 5월 30일
Just build the desired string array -- num2str works nicely here alto you have to ensure the values are in a column vector to avoid them being all strung out in one long string instead of as an array...
labels=num2str([1:5].','Weather Station %d');
plot(randn(5))
legend(labels,'location','best')
results in
Or, you can use the 'DisplayName' property of each line when you plot and legends will show automagically.

추가 답변 (1개)

Ameer Hamza
Ameer Hamza 2020년 5월 29일
Run this example
T = 1:3;
Legends = compose('Temp is %d', T);
hold on;
plot(rand(1,10));
plot(rand(1,10));
plot(rand(1,10));
legend(Legends)

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by