Kahibaro
Discord Login Register

Labels, Titles, Legends, and Annotations

Adding Text Information to Plots

When you present data, the text around a plot is often as important as the plotted lines themselves. Labels, titles, legends, and annotations turn a bare graphic into something that is readable and understandable. In this chapter you work with the most common text elements used in basic MATLAB plotting, and how they interact with figures and axes created in other chapters.

You will see only how to use these text commands with existing 2D plots. How to create the plots themselves and customize colors and lines is handled in other chapters.

Titles for Your Plots

Every important figure should have a clear title. MATLAB uses the title function to place a text label at the top of the current axes.

The simplest usage is to pass a character vector or a string:

matlab
x = 0:0.1:2*pi;
y = sin(x);
plot(x, y);
title('Sine wave');

If you need a longer, more descriptive title, you can write it as a single text string:

matlab
title('Sine wave over one period from 0 to 2\pi');

MATLAB interprets \pi using TeX formatting. You will see how TeX-like formatting affects text appearance later in this chapter.

You can also set a title with a line break by including the newline character \n:

matlab
title("Sine wave\nFull cycle");

When you call title, it returns a text object handle. This object lets you change properties after you create the title:

matlab
hTitle = title('Initial title');
hTitle.Color = 'red';
hTitle.FontSize = 14;

Many title properties are shared with other text elements, so learning to modify one of them is useful for all text in plots.

If you create multiple axes in the same figure, title applies to the current axes only. If you accidentally title the wrong subplot, call axes or use tiled layouts to make the correct axes current, then call title again.

Axis Labels

Titles describe the plot as a whole. Axis labels tell the reader what each axis represents and what units you use. MATLAB uses xlabel, ylabel, and zlabel for this purpose.

For a 2D plot, the most common pattern is:

matlab
plot(x, y);
xlabel('Time (s)');
ylabel('Amplitude (V)');

Like title, each of these functions returns a text object, so you can store and modify them:

matlab
hx = xlabel('Time (s)');
hy = ylabel('Amplitude (V)');
hx.FontWeight = 'bold';
hy.Color = [0 0.5 0];   % dark green

When you create 3D plots, zlabel works the same way:

matlab
plot3(x, y, z);
xlabel('X position (m)');
ylabel('Y position (m)');
zlabel('Z position (m)');

If you plan to use Greek letters or special symbols, you can include simple TeX sequences:

matlab
xlabel('\omega (rad/s)');
ylabel('Magnitude |H(\omega)|');

Axis labels are attached to the corresponding axes object. If you switch to other axes, calls to xlabel and ylabel affect those instead. This is particularly important when you work with subplots or tiled layouts.

Legends for Multiple Data Series

When you plot more than one data set in the same axes, a legend explains which line or marker corresponds to which quantity. MATLAB uses the legend function to create a labeled list of plot entries.

The simplest way is to plot the data first, then call legend with a label for each plotted series, in the same order:

matlab
x = 0:0.1:2*pi;
plot(x, sin(x), x, cos(x));
legend('sin(x)', 'cos(x)');

MATLAB creates a small box in the axes containing line samples and text labels. If you add or remove plots, you should update the legend to keep it accurate.

Instead of passing strings directly, you can call legend with plot object handles. This is useful if you want a legend for only some of the lines:

matlab
p1 = plot(x, sin(x), 'r');
hold on;
p2 = plot(x, cos(x), 'b');
p3 = plot(x, sin(2*x), 'k--');
hold off;
legend([p1 p3], {'sin(x)', 'sin(2x)'});

Here the legend includes only the first and third lines. This approach is important when you have many plotted objects and you do not want to label all of them.

You can place the legend automatically or specify a location keyword such as 'northwest', 'southeast', 'best', or 'outside' positions. For example:

matlab
legend('sin(x)', 'cos(x)', 'Location', 'northwest');

There is also the special location 'best' that tells MATLAB to choose a region where the legend overlaps the data the least:

matlab
legend('sin(x)', 'cos(x)', 'Location', 'best');

Like titles and labels, legend returns an object:

matlab
hLeg = legend('Data 1', 'Data 2');
hLeg.Box = 'off';          % remove legend border
hLeg.FontSize = 10;

This legend object has many properties that control its appearance, such as Orientation, NumColumns, and Location. You can set them either when you create the legend using name-value pairs or afterwards.

If you set new display names for plot objects, you can update the legend without reconstructing it manually. Many plotting functions have a DisplayName property that the legend can use:

matlab
p = plot(x, sin(x));
p.DisplayName = 'Sine';
legend('show');

Here legend('show') reads the DisplayName values of plotted objects and builds a legend automatically. This style becomes useful when you build scripts and want the legend text to follow your code changes.

Text Annotations Inside the Axes

Sometimes you want to label specific points, regions, or features inside the plotting area. For example, you might want to mark a peak value or write a short comment on a curve. MATLAB uses the text function to create text objects in data coordinates inside the axes.

The basic syntax is:

matlab
plot(x, y);
text(x0, y0, 'Peak');

Here x0 and y0 are given in the same units and scale as the plot data. If you write:

matlab
[~, idx] = max(y);
text(x(idx), y(idx), ' Maximum');

MATLAB places the label near the maximum point on the curve. The leading space in ' Maximum' provides a small horizontal offset from the point marker.

You can adjust the alignment using properties like HorizontalAlignment and VerticalAlignment to control where the text anchor sits relative to the given (x, y) coordinate:

matlab
text(x(idx), y(idx), 'max', ...
     'HorizontalAlignment', 'left', ...
     'VerticalAlignment', 'bottom');

This kind of precise placement helps keep text readable without overlapping data markers.

The text function returns a text object, which can be modified just like titles and axis labels:

matlab
t = text(1, 0.5, 'Note');
t.Color = 'red';
t.FontWeight = 'bold';

When you use text, you usually want the text to scale with the axes, so that when you zoom or pan the plot, the text moves with the data. Therefore, text uses data coordinates by default.

Figure and Axes Annotations

In addition to text, MATLAB provides higher-level annotation tools through the annotation function. The main difference is that annotation uses figure coordinates, not data coordinates. This means annotations keep their position relative to the figure window, instead of following the data when you zoom or pan.

The annotation function supports several shapes and text elements, such as arrows, double arrows, ellipses, rectangles, and text boxes. The coordinates are normalized to the figure window, so 0 means the left or bottom edge and 1 means the right or top edge.

For example, to create a text box near the top of the figure:

matlab
annotation('textbox', [0.15 0.75 0.3 0.1], ...
           'String', 'Important result', ...
           'FitBoxToText', 'on');

The four numbers in the vector [0.15 0.75 0.3 0.1] specify [x y width height] in normalized units. If you resize the figure, this box maintains its relative position.

To point to a feature visually, you can use an arrow:

matlab
annotation('textarrow', [0.3 0.5], [0.4 0.6], ...
           'String', 'Increase');

The two-element vectors [0.3 0.5] and [0.4 0.6] give the start and end point of the arrow, again in normalized figure coordinates.

Use annotation when you want figure-level commentary that does not depend on the data axis limits, such as notes in the margins, labels between subplots, or arrows that point across axes. For detailed point markers inside a single axes, prefer text.

Mathematical Symbols and Formatting in Labels

Many scientific and engineering plots need Greek letters, subscripts, superscripts, and simple mathematical formatting in titles, labels, and annotations. MATLAB supports a subset of TeX markup in most text properties.

Here are some common patterns:

To include Greek letters, use a backslash followed by the name of the letter, such as \alpha, \beta, \gamma, \mu, or \sigma:

matlab
xlabel('\alpha (deg)');
ylabel('\sin(\alpha)');

To write subscripts and superscripts, use the underscore _ and caret ^ symbols. You can group multiple characters using curly braces:

matlab
xlabel('V_{out} (V)');
ylabel('i^2 R');

Here V_{out} shows the word "out" as a subscript of V, and i^2 shows the 2 as a superscript.

You can also mix normal and italic formatting using \it for italic and \rm for roman:

matlab
title('\itExperimental data \rmversus model');

In many cases you do not need complex formatting. For simple numeric labels and plain text, regular characters work fine. However, using TeX sequences can make formulas or symbolic parts more clear and professional.

If you need advanced equation layout beyond what TeX markup provides inside labels, you can use Live Scripts for including formatted equations along with code and plots. Those techniques are explained in another chapter. For standard plot annotations, TeX-style markup is usually enough.

Positioning and Aligning Text

All text elements in a plot have position and alignment properties that control where and how the text appears.

For titles and axis labels, MATLAB selects default positions that usually work, even if you change axis limits or resize the figure. You rarely need to change the position manually. If you do, you can adjust the Position property of the text object. This property is a 3 element vector for 3D coordinates, or 2 element for 2D, corresponding to the reference point of the text.

For text created inside axes with text, position is given in data coordinates. When you zoom or pan, both the data and the text move together. Use horizontal and vertical alignment properties so the text sits comfortably next to the point you annotate:

matlab
t = text(5, 0.5, 'Label');
t.HorizontalAlignment = 'center';
t.VerticalAlignment = 'top';

For figure level annotations with annotation, position is normalized. If you want to position something relative to an axes, you can use the axes position to help compute the normalized coordinates. The Position property of an axes object tells you where it sits inside the figure in normalized units.

Understanding this difference between data coordinates and normalized figure coordinates is important when you mix text and annotation in the same figure. Use data coordinates for values that should move with the data, and normalized coordinates for elements that should stay fixed in the figure layout.

Editing Text Interactively

Besides writing code, you can also change titles, labels, legends, and annotations interactively in the figure window. When you create a plot from the Command Window or a script, you can click text items and type to change their contents. You can also drag legends and annotations to reposition them.

Interactive editing is useful for quick experiments and figuring out where text should go. However, if you need reproducible results or want to share the code, always bring your final edits back into the script using the text and legend functions. That way, anyone who runs your script gets the same labeled figure automatically.

Common Issues and How to Avoid Them

A frequent problem is missing or incorrect labels because the labels do not match the plotted data. If you alter which lines are shown or change their order, make sure you update the legend to keep the meaning clear. It is better to have no legend than a wrong legend.

Overlapping text is another common issue. Too many annotations in a small plot can make it hard to read. In such cases, consider making the figure larger, using fewer words, or separating information into multiple plots.

If text appears partly outside the axes or is cut off, it might be due to the axes limits or figure size. Zooming out or slightly adjusting the text position can fix this. For axis labels, MATLAB handles this situation automatically most of the time.

Finally, when printing or exporting figures, check that all text is still readable, with appropriate font sizes and contrast, especially if the figure will be printed in black and white. Adjust title and legend properties accordingly before you save or export the figure.

Key points to remember:
Use title, xlabel, ylabel, and zlabel to describe what the plot and each axis represent.
Create legends with legend using labels in the same order as plotted data, and update them when you change the plots.
Use text for annotations in data coordinates and annotation for figure level notes in normalized coordinates.
Apply simple TeX markup like \alpha, _, and ^ when you need mathematical symbols or subscripts and superscripts.
Keep labels concise, unambiguous, and readable, and verify them after zooming, resizing, or exporting a figure.

Views: 3

Comments

Please login to add a comment.

Don't have an account? Register now!