Search code examples
matlabmatlab-figure

Align text between two vertical lines in plot


How can I center text with text() (or any more suitable function) directly between specified spacers? Basically, I want to just use the x and y arguments in text(), but using the 'center' of the text.

I tried: Appending white spaces didn't work and shift based on number of characters was inconsistent, and the documentation doesn't mention anything about justifying strings to center.

%% create figure
x=[2 5]; %spacer var
figure; hold on;
axis([0 10 0 10])

%create lines based on spacer var
line([x(1) x(1)],ylim)
line([x(2) x(2)],ylim)

%silly formatting
grid on
axis square
xticks(0:10); yticks(0:10);
set(findall(gcf,'type','line'),'linewidth',3)

%generate text between vertical lines
y = ylim; %get ylimits
text(mean([0 x(1)]),y(2)*.8,'Label_1','FontSize',10)
text(mean([x(1) x(2)]),y(2)*.8,'Label_2','FontSize',10)

enter image description here


Solution

  • Text Alignment With Respect to Centre

    Using the 'HorizontalAlignment' property and setting it to 'center' may help in achieving the alignment in between the sections divided by the vertical lines. Here I initialize each text annotation to variables Text_1 and Text_2 and set their 'HorizontalAlignment' properties respectively.

    Code Snippet:

    Text_1 = text(mean([0 x(1)]),y(2)*.8,'Label_1','FontSize',10);
    Text_2 = text(mean([x(1) x(2)]),y(2)*.8,'Label_2','FontSize',10);
    
    set(Text_1,'HorizontalAlignment','center');
    set(Text_2,'HorizontalAlignment','center');
    

    Text Horizontal Alignment

    Full Script:

    %% create figure
    x=[2 5]; %spacer var
    figure; hold on;
    axis([0 10 0 10])
    
    %create lines based on spacer var
    line([x(1) x(1)],ylim)
    line([x(2) x(2)],ylim)
    
    %silly formatting
    grid on
    axis square
    xticks(0:10); yticks(0:10);
    set(findall(gcf,'type','line'),'linewidth',3)
    
    %generate text between vertical lines
    y = ylim; %get ylimits
    Text_1 = text(mean([0 x(1)]),y(2)*.8,'Label_1','FontSize',10);
    Text_2 = text(mean([x(1) x(2)]),y(2)*.8,'Label_2','FontSize',10);
    
    set(Text_1,'HorizontalAlignment','center');
    set(Text_2,'HorizontalAlignment','center');
    

    Ran using MATLAB R2019b