"plot" versus "text" command

4 views (last 30 days)
Michael W
Michael W on 6 Mar 2025
Edited: Adam Danz on 6 Mar 2025
Why does the following code:
x = [1, 2, 3, 4, 5];
y = [2, 4, 1, 5, 3];
labels = {'A', 'B', 'C', 'D', 'E'};
plot(x, y, 'LineStyle', 'none');
hold on;
text(x, y, labels, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle');
result in something different than this code?:
x = [1, 2, 3, 4, 5];
y = [2, 4, 1, 5, 3];
labels = {'A', 'B', 'C', 'D', 'E'};
text(x, y, labels, 'HorizontalAlignment', 'center', 'VerticalAlignment', 'middle')

Accepted Answer

Adam Danz
Adam Danz on 6 Mar 2025
Edited: Adam Danz on 6 Mar 2025
Text's property AffectAutoLimits is set to off by default. This means that the axes limits will not update if a text object is plotted outside of the axes limits. To auto-adjust the axes limits for text objects, include the name-value pair "AffectAutoLimits", "on" in the text(__) command.
x = [1, 2, 3, 4, 5];
y = [2, 4, 1, 5, 3];
labels = {'A', 'B', 'C', 'D', 'E'};
text(x, y, labels, ...
'AffectAutoLimits', 'on', ... % <-------------
'HorizontalAlignment', 'center', ...
'VerticalAlignment', 'middle')
When AffectAutoLimits is on, axes limits will be adjust to include the text anchor coordinates, not the full text extent. The text anchor is the coordinate that defines the text location but the text extent could extend outside of the axes limits. Auto-adjusting axes limits to include text extents is currently not possible .
Example:
figure
plot([-2 2],[1 1], 'rx')
text(-2, 1, 'LeftLabel', ...
'AffectAutoLimits', 'on', ...
'HorizontalAlignment', 'Center',...
'VerticalAlignment', 'bottom', ...
'Color','b')
text(2, 1, 'RightLabel', ...
'AffectAutoLimits', 'on', ...
'HorizontalAlignment', 'Center',...
'VerticalAlignment', 'bottom', ...
'Color','b')
box on

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!