| MATLAB® | ![]() |
| On this page… |
|---|
Creating Text Annotations with the text or gtext Function Mathematical Symbols, Greek Letters, and TEX Characters Using Character and Numeric Variables in Text |
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.

If you enable plot editing mode, you can create text annotations by clicking in an area of the graph or the figure background and entering text. You can also add text annotations from the command line, using the text or gtext function.
Using plot editing mode or gtext makes it easy to place a text annotation anywhere in a graph. Use the text function when you want to position a text annotation at a specific point in a data set.
Note 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. |
To create a text annotation using the text function, you must specify the text and its location in the graph, using x- and y-coordinates. You specify the coordinates in the units of the graph.
Use the gtext function when you want to position a text annotation at a specific point in the data space with the mouse.
For example, the following code creates text annotations at specific points in the Lotka-Volterra Predator-Prey Population Model graph.
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)
This example also illustrates how to create multiline text annotations with cell arrays.
You can also calculate the positions of text annotations in a graph. The following code adds annotations at three data points on a graph.
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.
Defining Symbols. For information on using symbols in text strings, see Mathematical Symbols, Greek Letters, and TEX Characters.

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
with A = 0.25,
α = 0.005, and t = 0 to 900.
t = 0:900; plot(t,0.25*exp(-0.005*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),...
'\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.
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.
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.
You can edit any of the text labels or annotations in a graph:
Double-click the string, or right-click the string and select Edit from the context menu.
An editing bar (|) appears next to the text.
Click anywhere outside the text edit box to end text editing.
Note 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. |
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.
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.
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.
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.

The text Interpreter property controls the interpretation of TEX characters. If you set this property to none, MATLAB interprets the special characters literally.
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.
For example, each row of the matrix PersonalData contains specific information about a person (note that all but the longest row are padded with a space so that each has the same number of columns).
PersonalData = ['Jack Straw ';'489 Main St.';'Wichita KN '];
To display the data, index into the desired row.
text(x1,y1,['Name: ',PersonalData(1,:)]) text(x2,y2,['Address: ',PersonalData(2,:)]) text(x3,y3,['City and State: ',PersonalData(3,:)])
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(x,y,key)
produce this output.

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.'])
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')

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}$$');

You can find out more about the LaTeX system at The LaTeX Project Web site, http://www.latex-project.org/.
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.
![]() | Adding Axis Labels to Graphs | Adding Arrows and Lines to Graphs | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |