Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

matlab - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...