Wrap in a legend with num2str

조회 수: 15 (최근 30일)
Gianluca Borgna
Gianluca Borgna 2019년 3월 24일
답변: Kelsey Dodge 2021년 7월 4일
Hi everyone!
I'm dealing with probability density functions.
In each figure i create i would like to add to legend the mean, the standard deviation and the cov (coefficient of variation). To do that i'm using the command num2str.
My code is:
%%
Excel_Caramagnabridge=load('caramagna.txt');
af_Caramagnabridge=Excel_Caramagnabridge(:,13);
Cover_Caramagna=Excel_Caramagnabridge(:,12);
CaramagnaEdges=3:0.3:12;
[Caramagna_mean, Caramagna_std]=normfit(af_Caramagnabridge);
Caramagna_cov=Caramagna_std/Caramagna_mean;
Caramagna_distr=normpdf(CaramagnaEdges,Caramagna_mean,Caramagna_std);
testCaramagna=chi2gof(Caramagna_distr);
figure; CaramagnaHist=histogram(af_Caramagnabridge,CaramagnaEdges,'Normalization','pdf');
hold on; f1=plot(CaramagnaEdges, Caramagna_distr, 'linewidth',2, 'color','b'); grid on;
legend([f1],['\mu = ' num2str(round(Caramagna_mean,2)) ' \sigma = ' num2str(round(Caramagna_std,2))], 'orientation','vertical',...
'location','northeast');
If i write in this way, the figure will report mean and std in a row. I just would like to wrap for each statistics.
How to do that?
Thanks!

채택된 답변

Rik
Rik 2019년 3월 24일
If you use a newline character ( char(10) ), you can wrap the text. Here is some example code:
figure(1),clf(1)
h=plot(rand(1,10));
mu=0.5;sigma=0.1;
legend(h,sprintf('\\mu=%.2f\n\\sigma=%.2f',mu,sigma))

추가 답변 (1개)

Kelsey Dodge
Kelsey Dodge 2021년 7월 4일
The above is great advice. I was looking to add two separate variables onto my graphics. The following worked:
First, I converted my variables to string characters. In this case, I was looking at displaying the mean and mode of my data set.
A1 = num2str(mm,3);
A2 = num2str(mo,3);
Then I called those variables in my legend like this:
legend('Draft (m)', sprintf('Mean = %s', A1), sprintf('Mode = %s',A2))
Which gave me the following:

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by