How to centre textboxes on the plot outline?

11 views (last 30 days)
Hi, I'm trying to create a plot with a couple of textbox annotations. Ideally, I'd like the text boxes to be centred on the boundary of the white plot area - not relative to the figure space. However, I'm struggling to find a way to easily do this - is there a means of finding these dimensions and not the dimensions of the entire figure? My code is as follows:
%Illustrates wavelength vs period
close all;
Fs = 8000; % samples per second
dt = 1/Fs; % seconds per sample
StopTime = 0.25; % seconds
t = (0:dt:StopTime-dt)'; % seconds
%%Sine wave:
Fc = 4; % hertz
x =sin(2*pi*Fc*t);
% Plot the signal versus time:
str = {'Period','T'};
dim = [0.457785714285714,0.883333333333335,0.127571428571429,0.0952380952381];
annotation('textbox',dim,'String',str,'FitBoxToText','on','Horizontalalignment','center','BackgroundColor', 'w');
str = {'Wavelength','\lambda'};
dim = [0.457785714285714,0.054761904761905,0.127571428571429,0.0952380952381];
annotation('textbox',dim,'String',str,'FitBoxToText','on','Horizontalalignment','center','BackgroundColor', 'w');
hold on;
zoom xon;
I hope what I am trying to achieve is clear from the plot, but as you can see it uses a very convoluted way of achieving a result which still doesn't look right.
Thanks in advance for your time.

Accepted Answer

Jakob B. Nielsen
Jakob B. Nielsen on 10 Mar 2020
First, make a handle for your figure:
Next, when you set the dimensions of your textbox, refer back to the ax.Position property:
dim = [(ax.Position(1)+ax.Position(3))/2,(ax.Position(2)+ax.Position(4)-0.0952380952381),0.127571428571429,0.0952380952381];
Here, I make sure the x start point of the box is the x-startpoint of the axes plus width of the axes divided by two (midway), and that the y start point of the box is the y start point of the axes plus the height of the axes, minus the height of the text box. See if you can make the same for the other box :)

More Answers (0)


Find more on Axes Appearance in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!