Mushi
Mushi

Reputation: 367

Alignment of text in matlab 'text' command

I want to print the following text on a matlab figure with ':' sign vertically aligned:

Total Events: 1234
Mean Value: 1234
Standard Deviation: 1234
1st Quartile: 1234
...
...

I am using text function and trying to insert spaces manually but they never seemed to be aligned perfectly and looks wavy.

Any helps, please.

Upvotes: 1

Views: 672

Answers (2)

Shai
Shai

Reputation: 114786

Use string format

strings = {'Total Events', 'Mean Value', 'Standard Deviation', '1st Quartile'};
max_len = max( cellfun( @numel, strings ) );
fs = sprintf( '%% %ds: 1234\n', max_len );
cellfun( @(x) fprintf(1,fs,x), strings );

Results with:

      Total Events: 1234
        Mean Value: 1234
Standard Deviation: 1234
      1st Quartile: 1234

As you can see the command that aligns to the right is

 sprintf( '% 18s: 1234', strings{1} )

So, eventually in your text command, instead of explicitly writing a string, you can format one using sprintf:

 text( 0, 0, sprintf( '% 18s: %d', strings{ii}, values(ii) );

Assuming you have strings - cell array of strings and same-length array values with corresponding values to print.

Upvotes: 2

Leonard Wayne
Leonard Wayne

Reputation: 195

You can use a fixed-width font and use a cell array to put the text on different lines:

text( 0, 0, { '      Total Events: 1234' ...
              '        Mean Value: 1234' ...
              'Standard Deviation: 1234' ...
              '      1st Quartile: 1234' }, 'FontName', 'FixedWidth' )

Upvotes: 2

Related Questions