Adding Text Annotations to Graphs

What Are Text Annotations?

Text annotations are boxes containing text strings that you compose. The box can have a border and a background, or be invisible. The text can be in any installed text font, and can include TeX or LaTeX markup. You can add free-form text annotations anywhere in a MATLAB figure to help explain your data or bring attention to specific points in your data sets.

As the following example shows, annotating a graph manually is easy in plot edit mode. When you enable plot editing, you can create text annotations by selecting the appropriate kind of annotation from the Insert menu, clicking in the graph or the figure background and then entering text. To insert textarrow annotations, you first drag out an arrow from tail to head, then type the text at the text cursor next to the tail,

You can also add text annotations from the command line, using the text or gtext function. The example illustrates how to use text.

Using plot editing mode or gtext makes it easy to place a text annotation where you want in a graph. Use the text function when you want to position a text annotation at a specific point within an axes for which you know the coordinates.

[warning]Text annotations created using the text or gtext function are anchored to the axes. Text annotations created in plot edit mode are not. If you move or resize your axes, you will have to reposition your text annotations. For more information, see Positioning Annotations in Data Space.[/warning]

Creating Text Annotations with the text or gtext Function

To create a text annotation using the text function, you must specify the text and its location within the axes, providing the x- and y-coordinates in the same Units that the graph uses (pixels, normalized, etc.).

Use the gtext function when you want to position a text annotation at a specific point in the data space with the mouse.

The following example adds text annotation, a title, and a legend to a graph of output from the Lotka-Volterra predator-prey population model. It also illustrates how to create multiline text annotations using cell arrays (also see the following section Text in Cell Arrays).

% Define initial conditions
t0 = 0;
tfinal = 15;
y0 = [20 20]';
% Simulate the differential equation
tfinal = tfinal*(1+eps);
[t,y] = ode23('lotka',[t0 tfinal],y0);
% Plot the two curves, storing handles to them
% so their DisplayNames can be set
hlines = plot(t,y);
% Compose and display two multiline text
% annotations as cell arrays
str1(1) = {'Many Predators;'};
str1(2) = {'Prey Population'};
str1(3) = {'Will Decline'};
text(7,220,str1)
str2(1) = {'Few Predators;'};
str2(2) = {'Prey Population'};
str2(3) = {'Will Increase'};
text(5.5,125,str2)
% Set DisplayNames for the lines for use by the legend
set(hlines(1),'Displayname','Prey')
set(hlines(2),'Displayname','Predator')
% Center a legend at the top of the graph
legend('Location','north')
% Add a title with bold style
title('Lotka-Volterra Predator-Prey Population Model',... 
  'FontWeight','bold')

To connect the text with the appropriate points on the plot, draw two annotation arrows by hand. First enter plot edit mode, either by typing

plotedit

in the Command Window or by clicking the Edit Plot icon in the figure toolbar. (Type plotedit again or click the icon again when you want to exit plot edit mode.)

Select Arrow from the Insert menu. Draw an arrow from each block of text to point to the lines, as shown here.

Calculating the Positions of Text Annotations

You can also calculate the positions of text annotations in a graph. The following code adds annotations at three data points on a graph.

t=0:pi/64:2*pi; 
plot(t,sin(t)); 
title('The Sine of 0 to 2\pi')
xlabel('t = 0 to 2\pi')
ylabel('sin(t)')

text(3*pi/4,sin(3*pi/4),...
     '\leftarrowsin(t) = .707',...
     'FontSize',16)

text(pi,sin(pi),'\leftarrowsin(t) = 0',...
     'FontSize',16)

text(5*pi/4,sin(5*pi/4),'sin(t) = -.707\rightarrow',... 
     'HorizontalAlignment','right',...
     'FontSize',16)

The HorizontalAlignment of the text string ‘sin(t) = -.707 \rightarrow’- is set to right to place it on the left side of the point [5*pi/4,sin(5*pi/4)] on the graph. For more information about aligning text annotations, see Text Alignment.

[help]Defining Symbols. For information on using symbols in text strings, see Mathematical Symbols, Greek Letters, and TEX Characters.[/help]

You can use text objects to annotate axes at arbitrary locations. Text is positioned using the data units of the axes. For example, suppose you plot the function y=Ae-αt with A = 0.25, α = 0.005, and t = 0 to 900.

t = 0:900;
plot(t,0.25*exp(-0.005*t))
xlabel('Time \musec')
ylabel('Amplitude')
title('\itAe^\alpha^t')


To annotate the point where the value of t = 300, calculate the text coordinates using the function you are plotting.

text(300,.25*exp(-0.005*300),...
title('\itAe^\alpha^t')['\bullet\leftarrow\...
fontname{times}0.25{\ite}^{-0.005{\itt}}' ...
' at {\itt} = 300'],'FontSize',14)

This statement defines the text Position property as

x = 300, y = 0.25e-0.005 × 300

The default text alignment places this point to the left of the string and centered vertically with the rectangle defined by the text Extent property. The following section provides more information about changing the default text alignment.

Text Alignment

The HorizontalAlignment and the VerticalAlignment properties control the placement of the text characters with respect to the specified x-, y-, and z-coordinates. The following diagram illustrates the options for each property and the corresponding placement of the text.

The default alignment is

  • HorizontalAlignment = ‘left’
  • VerticalAlignment = ‘middle’

The text String is not placed exactly on the specified Position. For example, the previous section showed a plot with a point annotated with text. Zooming in on the plot enables you to see the actual positioning of the text.

The small dot is the point specified by the text Position property. The larger dot is the bullet defined as the first character in the text String property.

Example — Aligning Text

Suppose you want to label the minimum and maximum values in a plot with text that is anchored to these points and that displays the actual values. This example uses the plotted data to determine the location of the text and the values to display on the graph. One column from the peaks matrix generates the data to plot.

Z = peaks;
h = plot(Z(:,33));

The first step is to find the indices of the minimum and maximum values to determine the coordinates needed to position the text at these points (get, find). Then create the string by concatenating the values with a description of what the values are.

x = get(h,'XData'); 		% Get the plotted data
y = get(h,'YData');
imin = find(min(y) == y);		% Find the index of the min and max
imax = find(max(y) == y);
text(x(imin),y(imin),[' Minimum = ',num2str(y(imin))],...
	'VerticalAlignment','middle',...
	'HorizontalAlignment','left',...
	'FontSize',14)
text(x(imax),y(imax),['Maximum =  ',num2str(y(imax))],...
	'VerticalAlignment','bottom',...
	'HorizontalAlignment','right',...
	'FontSize',14)


The text function positions the string relative to the point specified by the coordinates, in accordance with the settings of the alignment properties. For the minimum value, the string appears to the right of the text position point; for the maximum value the string appears above and to the left of the text position point. The text always remains in the plane of the computer screen, regardless of the view.

Editing Text Objects

You can edit any of the text labels or annotations in a graph:

  • Start plot edit mode.

Double-click the string, or right-click the string and select Edit from the context menu.

An editing bar (|) appears next to the text.

  • Make any changes to the text.
  • Click anywhere outside the text edit box to end text editing.

[warning]To create special characters in text, such as Greek letters or mathematical symbols, use TEX sequences. See the text string property for a table of characters you can use. If you create special characters by using the Font dialog box (available via text objects’ context menus, and also found in the Property Editor) and selecting the Symbol font family, you cannot edit that text object using MATLAB commands.[/warning]

Mathematical Symbols, Greek Letters, and TEX Characters

You can include mathematical symbols and Greek letters in text using TEX-style character sequences. This section describes how to construct a TEX character sequence.

Two Levels of MATLAB TEX Support

There are two levels of TEX support, controlled by the text Interpreter property:

  • ‘tex’ — Support for a subset of TEX markup
  • ‘latex’ — Support for TEX and LATEX markup

If you do not want the characters interpreted as TEX markup, then set the interpreter property to ‘none’.

Available Symbols and Greek Letters

For a list of symbols and the character sequences used to define them, see the table of available TEX characters in the Text Properties reference page.

In general, you can define text that includes symbols and Greek letters using the text function, assigning the character sequence to the String property of text objects. You can also include these character sequences in the string arguments of the title, xlabel, ylabel, and zlabel functions.

Example — Using a Mathematical Expression to Title a Graph

This example uses TEX character sequences to create graph labels. The following statements add a title and x- and y-axis labels to an existing graph.

title('{\itAe}^{-\alpha\itt}sin\beta{\itt} \alpha<<\beta')
xlabel('Time \musec.')
ylabel('Amplitude')


The backslash character (\) precedes all TEX character sequences. Looking at the string defining the title illustrates how to use these characters.

Controlling the Interpretation of TEX Characters

The text Interpreter property controls the interpretation of TEX characters. If you set this property to none, MATLAB interprets the special characters literally.

Specifying Text Color in TeX Strings

Use the \color modifier to change the color of characters following it from the previous color (which is black by default). Syntax is:

\color{colorname} for the eight basic named colors (red, green, yellow, magenta, blue, black, white), and plus the four Simulink® colors (gray, darkGreen, orange, and lightBlue)

Note that short names (one-letter abbreviations) for colors are not supported by the \color modifier.

  • \color[rgb]{r g b} to specify an RGB triplet with values between 0 and 1 as a cell array

For example,

text(.1,.5,['\fontsize{16}black {\color{magenta}magenta '...
'\color[rgb]{0 .5 .5}teal \color{red}red} black again'])

Specifying Subscript and Superscript Characters

The subscript character "_" and the superscript character "^" modify the character or substring defined in braces immediately following.

To print the special characters used to define the TeX strings when Interpreter is Tex, prefix them with the backslash "\" character: \\, \{, \} \_, \^.

[important]See the text reference page for more information.[/important]

When Interpreter is set to none, no characters in the String are interpreted, and all are displayed when the text is drawn.

When Interpreter is set to latex, MATLAB provides a complete LaTEX interpreter for text objects. See the Interpreter property for more information.

Using Character and Numeric Variables in Text

Any string variable is a valid specification for the text String property. This section illustrates how to use matrix, cell array, and numeric variables as arguments to the text function.

Text in Character Arrays

For example, each row of the matrix PersonalData contains specific information about a person, padding all but the longest row with a space so that each has the same number of columns).

PersonalData = ['Jack Straw ';'489 Main St';'Wichita KS '];

To display the data, index into the desired row.

text(.3,.5,['Name: ',PersonalData(1,:)])
text(.3,.45,['Address: ',PersonalData(2,:)])
text(.3,.4,['City and State: ',PersonalData(3,:)])

Text in Cell Arrays

Using a cell array enables you to create multiline text with a single text object. Each cell does not need to be the same number of characters. For example, the following statements,

key(1)={'{\itAe}^{-\alpha\itt}sin\beta{\itt}'};
key(2)={'Time in \musec'};
key(3)={'Amplitude in volts'};
text(.1,.8,key)

produce this output.

Numeric Variables

You can specify numeric variables in text strings using the num2str (number to string) function. For example, if you type on the command line

x = 21;
['Today is the ',num2str(x),'st day.']

The three separate strings concatenate into one.

Today is the 21st day.

Since the result is a valid string, you can specify it as a value for the text String property.

text(xcoord,ycoord,['Today is the ',num2str(x),'st day.'])

Example — Multiline Text

You can input multiline text strings using cell arrays. Simply define a string variable as a cell array with one line per cell. This example defines two cell arrays, one used for a uicontrol and the other as text.

str1(1) = {'Center each line in the Uicontrol'};
str1(2) = {'Also check out the textwrap function'};
str2(1) = {'Each cell is a quoted string'};
str2(2) = {'You can specify how the string is aligned'};
str2(3) = {'You can use LaTeX symbols like \pi \chi \Xi'};
str2(4) = {'\bfOr use bold \rm\itor italic font\rm'};
str2(5) = {'\fontname{courier}Or even change fonts'};
plot(0:6,sin(0:6))
uicontrol('Style','text','Position',[80 80 200 30],...
          'String',str1);
text(5.75,sin(2.5),str2,'HorizontalAlignment','right')

Example — Using LaTeX to Format Math Equations

The LaTeX markup language evolved from TEX, and has a superset of its capabilities. LaTeX gives you more elaborate control over specifying and styling mathematical symbols.

The following example illustrates some LaTeX typesetting capabilities when used with the text function. Because the default interpreter is for TEX, you need to specify the parameter-value pair 'interpreter','latex' when typesetting equations such as are contained in the following script:

%% LaTeX Examples--Some well known equations rendered in LaTeX
%
figure('color','white','units','inches','position',[2 2 4 6.5]);
axis off

%% A matrix; LaTeX code is
% \hbox {magic(3) is } \left( {\matrix{ 8 & 1 & 6 \cr 
% 3 & 5 & 7 \cr 4 & 9 & 2 } } \right)
h(1) = text('units','inch', 'position',[.2 5], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    ['$$\hbox {magic(3) is } \left( {\matrix{ 8 & 1 & 6 \cr'...
    '3 & 5 & 7 \cr 4 & 9 & 2 } } \right)$$']);

%% A 2-D rotation transform; LaTeX code is
%  \left[ {\matrix{\cos(\phi) & -\sin(\phi) \cr
%  \sin(\phi) & \cos(\phi) \cr}}
%  \right] \left[ \matrix{x \cr y} \right]  
%  
%  $$ \left[ {\matrix{\cos(\phi) 
%  & -\sin(\phi) \cr \sin(\phi) & \cos(\phi)  % \cr}}
%  \right] \left[ \matrix{x \cr y} \right] $$ 
%
h(2) = text('units','inch', 'position',[.2 4], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    ['$$\left[ {\matrix{\cos(\phi) & -\sin(\phi) \cr'...
    '\sin(\phi) & \cos(\phi) \cr}} \right]'...
    '\left[ \matrix{x \cr y} \right]$$']);

%% The Laplace transform; LaTeX code is
%  L\{f(t)\}  \equiv  F(s) = \int_0^\infty\!\!{e^{-st}f(t)dt}  
%  $$ L\{f(t)\} \equiv  F(s) = \int_0^\infty\!\!{e^{-st}f(t)dt} $$
%  The Initial Value Theorem for the Laplace transform:
%  \lim_{s \rightarrow \infty} sF(s) = \lim_{t \rightarrow 0} f(t)
%  $$ \lim_{s \rightarrow \infty} sF(s) = \lim_{t \rightarrow 0}
%  f(t) $$
%
h(3) = text('units','inch', 'position',[.2 3], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    ['$$L\{f(t)\}  \equiv  F(s) = \int_0^\infty\!\!{e^{-st}'...
    'f(t)dt}$$']);

%% The definition of e; LaTeX code is
%  e = \sum_{k=0}^\infty {1 \over {k!} }
%  $$ e = \sum_{k=0}^\infty {1 \over {k!} } $$
%
h(4) = text('units','inch', 'position',[.2 2], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    '$$e = \sum_{k=0}^\infty {1 \over {k!} } $$');

%% Differential equation
% The equation for motion of a falling body with air resistance
% LaTeX code is
%  m \ddot y = -m g + C_D \cdot {1 \over 2} \rho {\dot y}^2 \cdot A
%  $$ m \ddot y = -m g + C_D \cdot {1 \over 2} \rho {\dot y}^2
%  \cdot A  $$
%
h(5) = text('units','inch', 'position',[.2 1], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    ['$$m \ddot y = -m g + C_D \cdot {1 \over 2}'...
    '\rho {\dot y}^2 \cdot A$$']); 

%% Integral Equation; LaTeX code is
%  \int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4}  
%  $$ \int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4} $$  
%  
h(6) = text('units','inch', 'position',[.2 0], ...
    'fontsize',14, 'interpreter','latex', 'string',...
    '$$\int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4}$$');   


[tip]You can find out more about the LaTeX system at The LaTeX Project Web site,
latex-project.org[/tip]

Drawing Text in a Box

When you use the text function to display a character string, the string's position is defined by a rectangle called the Extent of the text. You can display this rectangle either as a box or a filled area. For example, you can highlight contour labels to make the text easier to read.

[x,y] = meshgrid(-1:.01:1);
z = x.*exp(-x.^2-y.^2);
[c,h]=contour(x,y,z);
h = clabel(c,h);
set(h,'BackgroundColor',[1 1 .6])


For additional features, see the following text properties:

  • BackgroundColor — Color of the rectangle's interior ('none' by default)
  • EdgeColor — Color of the rectangle's edge ('none' by default)
  • LineStyle — Style of the rectangle's edge line (first set EdgeColor)
  • LineWidth — Width of the rectangle's edge line (first set EdgeColor)
  • Margin — Increase the size of the rectangle by adding a margin to the text extent.

You may also like...