Textboxes with offset/buffer/margin from edge of plot area same as legend

5 views (last 30 days)
I am looking for add textboxes to plots and would like the margin/buffer/margin/white space between the edges of the textbox to be the same as the legend.
I found the following function which uses the same legend location values (south west...) and a normalized buffer of 1/50 but this doesn't line up.
The value of
ax.Position(1)+ax.Position(3)-(legend().Position(1)+legend().Position(3))
isn't constant when resized nor is the offset/buffer constant. It doesnt seem to be pixel, inches, or normalized. What algorithim is used to find this space?
I've also used the legend properties to determine the location of a northwest text box from a northeast legend and it seems like I can replicate the white space using it but it does not autosize:
loglog(1:100,1:100)
legend
ax=gca;
width = 0.1;
height = 0.05;
x_pos = ax.Position(1) + ax.Position(3) - (legend().Position(1) + legend().Position(3)) + ax.Position(1);
y_pos = legend().Position(2)+legend().Position(4) - height;
a=annotation('textbox',[x_pos, y_pos,width, height],'String',"text");
Is there a newer way to set the location of a textbox using the same value so that it autosizes like the legend?

Answers (1)

Ruchika Parag
Ruchika Parag on 9 Jul 2025
Hi @Thomas, MATLAB doesn’t currently support a built-in way to position annotation('textbox', ...) elements using the same logic as legends (e.g., 'northwest', 'southeast', etc.), and there’s no auto-alignment or margin-matching feature either. However, you can get pretty close by manually calculating the position relative to the axis and legend objects.
Here's one approach that replicates the spacing of the legend and also allows the textbox to autosize to its content:
x = linspace(0,2*pi,1000);
y = sin(x-2);
plot(x, y);
grid on;
ax = gca;
lgd = legend('y = sin(x - 2)');
% Create an annotation textbox with autosizing
an = annotation('textbox', [.1 .1 .1 .1], ...
'String', 'Info Box', ...
'FitBoxToText', 'on', ...
'BackgroundColor', 'white');
% Compute position to match spacing like the legend
newx = ax.InnerPosition(1) + ax.InnerPosition(3) ...
- (lgd.Position(1) + lgd.Position(3)) + ax.InnerPosition(1);
newy = lgd.Position(2) + lgd.Position(4) - an.Position(4);
% Update textbox position
an.Position = [newx, newy, an.Position(3), an.Position(4)];
This uses FitBoxToText = 'on' to autosize the textbox and places it relative to the legend so the white space/margin looks similar. If the figure is resized, though, you’ll need to re-calculate the position again—there’s no built-in dynamic tracking between the annotation and legend.
Hope this helps!

Tags

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!