Annotations & Text
A figure that needs a paragraph of explanation beside it isn't finished. Good annotations put the explanation on the figure: the peak value next to the peak, a dashed line at the safety limit, a label beside each data point. Plot Formatting introduced title, axis labels, legend and a first text call; this lesson covers the full toolkit.
| Tool | Positioned in | Use it for |
|---|---|---|
title, xlabel, ylabel, zlabel |
The axes | Naming the plot and its axes |
text(x, y, str) |
Data coordinates | Labels that belong to a data point |
xline(x), yline(y) |
Data coordinates | Reference lines (limits, means, events), optionally labelled |
legend |
The axes | Naming the plotted series |
annotation(type, x, y) |
Figure coordinates (0–1) | Arrows, boxes and shapes that may cross axes |
gtext(str) |
Where you click | Placing a label interactively with the mouse |
Rich text in labels
Every text function interprets a subset of TeX markup by default, so Greek letters, sub- and superscripts and simple styling need no special tools:
| You type | You get |
|---|---|
x^2, e^{-t/\tau} |
Superscripts (braces group several characters) |
v_0, T_{max} |
Subscripts |
\alpha \beta \pi \omega \Delta |
Greek letters |
\circ, \pm, \leq, \rightarrow |
Degree sign, plus-minus, ≤, arrows |
{\bf bold}, {\it italic} |
Bold and italic parts |
{\color{red} warning} |
Coloured text |
Two related options are worth knowing. 'Interpreter', 'latex' switches to full LaTeX math (write '$\frac{1}{2}#39;; MATLAB supports it fully, Octave's support depends on the graphics toolkit). 'Interpreter', 'none' turns markup off, which you need for text such as file names: in title('run_2024_final.csv') every _ would otherwise make the next character a subscript.
A cell array gives a multi-line title or label: title({'Damped oscillation', 'k = 0.6 s^{-1}'}). In MATLAB, subtitle('...') adds a smaller second line under the title (Octave 11 doesn't have subtitle; use the cell-array form).
Labels built from data
Annotation text usually contains numbers computed by the program, so it's built with sprintf (or num2str) and the usual format codes. Here the label for the highest point of a damped oscillation is computed first:
t = 0:0.01:5;
y = 3 * exp(-0.6*t) .* sin(2*pi*t);
[ymax, k] = max(y);
label = sprintf('\\leftarrow peak %.2f at t = %.2f s', ymax, t(k));
disp(label)
fprintf('After the peak, y stays >= 0 until t = %.2f s\n', t(find(y(k:end) < 0, 1) + k - 2));\leftarrow peak 2.59 at t = 0.23 s
After the peak, y stays >= 0 until t = 0.50 s
Inside sprintf, a backslash starts an escape sequence such as \n, so a TeX command needs a doubled backslash (\\leftarrow); the result contains a single \leftarrow, which the plot then turns into an arrow. Now the figure:
t = 0:0.01:5;
y = 3 * exp(-0.6*t) .* sin(2*pi*t);
[ymax, k] = max(y);
plot(t, y, 'LineWidth', 1.5)
hold on
plot(t(k), ymax, 'ro', 'MarkerFaceColor', 'r')
text(t(k) + 0.08, ymax, sprintf('\\leftarrow peak %.2f at t = %.2f s', ymax, t(k)))
yline(0, ':')
hold off
ylim([-3 3])
xlabel('Time (s)'); ylabel('Displacement (cm)')
title({'Damped oscillation', 'y = 3e^{-0.6t} sin(2\pi t)'})Controlling text placement
text returns a handle, and its properties decide how the string sits relative to the point you gave:
| Property | Values | Meaning |
|---|---|---|
'HorizontalAlignment' |
'left' (default), 'center', 'right' |
Which end of the text is at x |
'VerticalAlignment' |
'middle' (default), 'top', 'bottom', 'baseline' |
Which part is at y |
'FontSize', 'FontWeight' |
12, 'bold' |
Size in points, weight |
'Color', 'BackgroundColor' |
'r', [1 1 0.8] |
Text and box colours |
'Rotation' |
90 |
Angle in degrees |
text also accepts vectors of positions and a cell array of strings, labelling many points in one call. Combined with alignment, that gives labels centred just above each marker:
cities = {'Oslo', 'Lyon', 'Porto', 'Graz', 'Turku'};
area_km2 = [454 48 41 127 246];
pop_k = [709 522 232 291 201];
scatter(area_km2, pop_k, 'filled')
text(area_km2, pop_k + 25, cities, 'HorizontalAlignment', 'center')
xlabel('Area (km^2)'); ylabel('Population (thousands)')
xlim([0 500]); ylim([100 800])cities = {'Oslo', 'Lyon', 'Porto', 'Graz', 'Turku'};
area_km2 = [454 48 41 127 246];
pop_k = [709 522 232 291 201];
density = 1000 * pop_k ./ area_km2; % people per km^2
[~, order] = sort(density, 'descend');
for k = order
fprintf('%-6s %6.0f people/km^2\n', cities{k}, density(k));
endLyon 10875 people/km^2
Porto 5659 people/km^2
Graz 2291 people/km^2
Oslo 1562 people/km^2
Turku 817 people/km^2
Reference lines: xline and yline
xline(x) draws a vertical line across the whole axes at x, and yline(y) a horizontal one; both stay put when you zoom or change the limits. An optional line spec and a label make them self-explanatory:
hours = 0:23;
load_kw = [31 29 28 28 30 36 48 62 70 74 76 78 80 79 77 75 73 76 82 85 78 64 50 38];
plot(hours, load_kw, '-o', 'LineWidth', 1.2)
yline(75, 'r--', 'Contract limit 75 kW');
yline(mean(load_kw), 'k:', 'Mean');
xline(12, '-', 'Noon');
xlabel('Hour'); ylabel('Load (kW)')
xlim([0 23])hours = 0:23;
load_kw = [31 29 28 28 30 36 48 62 70 74 76 78 80 79 77 75 73 76 82 85 78 64 50 38];
over = hours(load_kw > 75);
fprintf('Mean load: %.1f kW\n', mean(load_kw));
fprintf('Above the limit at hours: %s\n', mat2str(over));
fprintf('Worst hour: %d:00 with %d kW\n', hours(load_kw == max(load_kw)), max(load_kw));Mean load: 60.3 kW
Above the limit at hours: [10 11 12 13 14 17 18 19 20]
Worst hour: 19:00 with 85 kW
xline and yline accept vectors too (xline([6 18]) draws two lines). MATLAB R2023a and later also have xregion and yregion for shaded bands; in Octave, draw a band with patch or fill.
More about legends
A legend is an annotation too, and a few options make it fit better:
x = linspace(0, 2*pi, 100);
h1 = plot(x, sin(x), 'DisplayName', 'sin x');
hold on
h2 = plot(x, cos(x), '--', 'DisplayName', 'cos x');
plot(x, zeros(size(x)), 'k:') % a helper line, no legend entry wanted
hold off
legend([h1 h2], 'Location', 'southwest') % only these two, named by DisplayName'DisplayName'on each plot call names the series where it's created, so the legend stays correct if you reorder code.legend('show')(orlegendwith only options) builds the legend from those names.legend([h1 h2], ...)with handles lists only those objects, which is how you leave helper lines out. Another way is to pass'HandleVisibility', 'off'when plotting the helper line.'Location'takes compass names ('northeast','south'…),'best'and'...outside'variants such as'eastoutside', which put the legend beside the axes.legend boxoffremoves the frame andlegend offdeletes the legend.
Figure-level annotations
annotation draws shapes in normalised figure coordinates: (0, 0) is the bottom-left corner of the figure window and (1, 1) the top-right, regardless of the axes' data. That's useful for arrows from a note in the margin to a point in the plot, or for a box spanning several subplots:
| Call | Draws |
|---|---|
annotation('arrow', [x1 x2], [y1 y2]) |
An arrow from (x1, y1) to (x2, y2) |
annotation('doublearrow', ...), annotation('line', ...) |
Two-headed arrow, plain line |
annotation('textarrow', [x1 x2], [y1 y2], 'String', 'note') |
An arrow with text at its tail |
annotation('textbox', [x y w h], 'String', 'note') |
A text box (position and size) |
annotation('rectangle', [x y w h]), annotation('ellipse', ...) |
Shapes |
The catch is that you usually know where the point is in data units. The axes occupy the rectangle given by their Position property ([left bottom width height] in normalised units; for a single default axes it is [0.13 0.11 0.775 0.815]), so a little arithmetic converts between the two:
pos = [0.13 0.11 0.775 0.815]; % get(gca, 'Position') for default axes
xl = [0 5]; yl = [-3 3]; % xlim and ylim of the plot
[xn, yn] = data2norm(0.23, 2.59, pos, xl, yl);
fprintf('Peak in figure units: (%.3f, %.3f)\n', xn, yn);
% annotation('textarrow', [xn + 0.2, xn + 0.01], [yn - 0.1, yn], 'String', 'peak')
function [xn, yn] = data2norm(x, y, pos, xl, yl)
% Convert data coordinates to normalised figure coordinates.
xn = pos(1) + (x - xl(1)) / (xl(2) - xl(1)) * pos(3);
yn = pos(2) + (y - yl(1)) / (yl(2) - yl(1)) * pos(4);
endPeak in figure units: (0.166, 0.869)
Because annotations are attached to the figure, not the axes, they don't move when you pan, zoom or change the limits. If the label belongs to a data point, prefer text; reach for annotation when the drawing must sit outside the axes or span several of them.
Summary
textplaces strings at data coordinates; alignment properties fine-tune where they sit, and cell arrays label many points at once.- TeX markup (
^,_,\alpha,{\bf ...}) works in all text;'Interpreter', 'none'shows underscores literally. - Build labels with
sprintf, doubling backslashes for TeX commands. xline/ylinedraw labelled reference lines;'DisplayName'keeps legends in sync with the data.annotationworks in figure coordinates (0–1): convert from data units with the axes'Position.
Next: Images & Colormaps. Learn more: Matplotlib annotations covers the same ideas in Python.
Test yourself
In which coordinates does text(x, y, str) place its string?
- Pixels from the top-left of the screen
- Normalised figure units from 0 to 1
- Data coordinates of the current axes
- Centimetres on the printed page
Why does title('data_set_1') show subscripts?
- Titles are always LaTeX
- The default TeX interpreter treats
_as a subscript - Underscores are not allowed in titles
- It's a bug in MATLAB
Which call draws a horizontal dashed red line at y = 75 labelled 'limit'?
xline(75, 'r--', 'limit')yline(75, 'r--', 'limit')hline(75, 'limit')line(75, 'r--')