Help Center Help Center

  • Help Center
  • Trial Software
  • Product Updates
  • Documentation

Add Annotations to Chart

Annotations are extra information added to a chart to help identify important information. This example first explains the different types of annotations, and then shows you how to add circles and text arrows to a chart.

Types of Annotations

Use the annotation function to add annotations to a chart. The first input to the function specifies the type of annotation you want to create.

If you specify the type as 'line' , 'arrow' , 'doublearrow' , or 'textarrow' , then the second input is the starting and ending x positions of the annotation. The third input is the starting and ending y positions of the annotation. For example, annotation('line',[x_begin x_end],[y_begin y_end]) .

If you specify the type as 'rectangle' , 'ellipse' , or 'textbox' , then the second argument is the location and size. For example, annotation('rectangle',[x y w h]) .

Annotations use normalized figure units and can span multiple axes in a figure.

Create Simple Plot

Define and plot functions f(x) and g(x) .

Figure contains an axes object. The axes object contains 2 objects of type line.

Circle Annotations

Add a circle to the chart to highlight where f(x) and g(x) are equal. To create a circle, use the 'ellipse' option for the annotation type.

Customize the circle by setting properties of the underlying object. Return the Ellipse object as an output argument from the annotation function. Then, access properties of the object using dot notation. For example, set the Color property.

Figure contains an axes object. The axes object contains 2 objects of type line.

Text Arrow Annotations

Add a text arrow to the chart using the 'textarrow' option for the annotation type.

You can customize the text arrow by setting properties of the underlying object. Return the TextArrow object as an output argument from the annotation function. Then, access properties of the object using dot notation. For example, set the String property to the desired text and the Color property to a color value.

Figure contains an axes object. The axes object contains 2 objects of type line.

text | annotation

Related Topics

Open Example

You have a modified version of this example. Do you want to open this example with your edits?

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Asia Pacific

Contact your local office

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

annotation in matlab plot

I just wonder how to add annotation in matlab plot? Here is my code:

But the arrow points to the wrong place. How can I fix it? And any better idea for annotating a plot?

Thanks and regards!

I just saw from the help document:

annotation('line',x,y) creates a line annotation object that extends from the point defined by x(1),y(1) to the point defined by x(2),y(2), specified in normalized figure units.

In my code, I would like the arrow pointing to the point (x,y) that is drawn by plot(), but annotation interprets the values of x and y as in normalized figure units. So I think that is what causes the problem. How can I specify the correct coordinates to annotation?

Tim's user avatar

3 Answers 3

First, you need to find the position of the axes in normalized figure units. Fortunately, they're set to 'normalized' by default.

axPos is [xMin,yMin,xExtent,yExtent]

Then, you get the limits, i.e. min and max of the axes.

Finally, you can calculate the annotation x and y from the plot x and y.

Use xAnnotation and yAnnotation as x and y coordinates for your annotation.

Jonas's user avatar

Another way to get normalized figure coordinates is to use Data space to figure units conversion (ds2nfu) submission on FileExchange.

yuk's user avatar

I had some trouble understanding the normalized coordinates, until I realized that the coordinates (0,0) and (1,1) are respectively the lower left corner and upper right corner of the COMPLETE plot window, not just of the plot. The below snippet and the screenshot might help others who have been wondering where the 0 starts and the 1 ends.

Plot with arrow coordinates (0,0) and (1,1)

lokxs's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .

Not the answer you're looking for? Browse other questions tagged matlab plot annotations or ask your own question .

Hot Network Questions

annotation text plot matlab

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Help Center Help Center

Create annotations

Description

annotation( lineType , x , y ) creates a line or arrow annotation extending between two points in the current figure. Specify lineType as 'line' , 'arrow' , 'doublearrow' , or 'textarrow' . Specify x and y as two-element vectors of the form [x_begin x_end] and [y_begin y_end] , respectively.

annotation( lineType ) creates the annotation in the default position between the points (0.3,0.3) and (0.4,0.4) .

annotation( shapeType , dim ) creates a rectangle, ellipse, or text box annotation with a particular size and location in the current figure. Specify shapeType as 'rectangle' , 'ellipse' , or 'textbox' . Specify dim as a four-element vector of the form [x y w h] . The x and y elements determine the position and the w and h elements determine the size.

annotation( shapeType ) creates the annotation in the default position so that the lower left corner is at (0.3,0.3) and the width and height are both 0.1 .

annotation( ___ , Name,Value ) creates the annotation and specifies properties as name-value pair arguments. Different types of annotations support different properties. You can specify properties with any of the input argument combinations in the previous syntaxes.

annotation( container , ___ ) creates the annotation in the figure, uipanel, or uitab specified by container , instead of in the current figure.

an = annotation( ___ ) returns the annotation object. The type of object returned depends on first input argument. Use an to modify properties of the object after it is created. You can specify an output argument with any of the previous syntaxes.

collapse all

Create Text Arrow Annotation

Create a simple line plot and add a text arrow to the figure. Specify the text arrow location in normalized figure coordinates, starting at the point (0.3,0.6) and ending at (0.5,0.5) . Specify the text description by setting the String property.

Figure contains an axes object. The axes object contains an object of type line.

Create Text Box Annotation

Create a simple line plot and add a text box annotation to the figure. Specify the text description by setting the String property. Force the box to fit tightly around the text by setting the FitBoxToText property to 'on' .

Figure contains an axes object. The axes object contains an object of type line.

Create a text box annotation without setting the FitBoxToText property. The text box uses the specified width and height and wraps text as needed.

Figure contains an axes object. The axes object contains an object of type line.

Create Text Box Annotation with Multiline Text

Create a text box annotation with multiline text by setting the String property to a cell array. Each element of the cell array displays on a separate line. Force the box to fit tightly around the text by setting the FitBoxToText property to 'on' .

Figure contains an axes object. The axes object contains an object of type line.

Create Rectangle Annotation

Create a stem plot and add a rectangle annotation to the figure. Change the color of the rectangle outline by specifying the Color property.

Figure contains an axes object. The axes object contains an object of type stem.

Add a second rectangle annotation to the figure. Specify the fill color by setting the FaceColor property. Add transparency by setting the FaceAlpha property to a value between 0 (completely transparent) and 1 (completely opaque).

Figure contains an axes object. The axes object contains an object of type stem.

Create Ellipse Annotation

Create a simple line plot and add an ellipse annotation to the figure. Specify dim as the size and location of the smallest rectangle that encloses the ellipse.

Figure contains an axes object. The axes object contains an object of type line.

Draw a red rectangle using the same dimensions to show how the ellipse fills the rectangular area.

Figure contains an axes object. The axes object contains an object of type line.

Combine Two Types of Annotations

Create a simple line plot. Then, add a bent arrow to the graph by combining a line and an arrow annotation.

Figure contains an axes object. The axes object contains an object of type line.

Modify Annotation After Creation

Add a text arrow to a figure and return the annotation text arrow object, a .

Figure contains an axes object. The axes object contains an object of type line.

Modify properties of the annotation text arrow using a . For example, change the color to red and the font size to 14 points.

Figure contains an axes object. The axes object contains an object of type line.

See the annotation property pages for a list of properties for each type of annotation.

Input Arguments

Linetype — type of line annotation 'line' | 'arrow' | 'doublearrow' | 'textarrow'.

Type of line annotation, specified as one of these values.

shapeType — Type of shape annotation 'rectangle' | 'ellipse' | 'textbox'

Type of shape annotation, specified as one of these values.

x — Beginning and ending x -coordinates two-element vector of the form [x_begin x_end]

Beginning and ending x -coordinates, specified as a two-element vector of the form [x_begin x_end] . Together the x and y input arguments determine the endpoints of the line, arrow, double arrow, or text arrow annotation. The annotation extends from the point ( x_begin , y_begin ) to ( x_end , y_end ).

By default, the units are normalized to the figure. The lower left corner of the figure maps to (0,0) and the upper right corner maps to (1,1) . To change the units, use the Units property.

Example: x = [.3 .5]

y — Beginning and ending y -coordinates two-element vector of the form [y_begin y_end]

Beginning and ending y -coordinates, specified as a two-element vector of the form [y_begin y_end] . Together the x and y input arguments determine the endpoints of the line, arrow, double arrow, or text arrow annotation. The annotation extends from the point ( x_begin , y_begin ) to ( x_end , y_end ).

Example: y = [.3 .5]

dim — Size and location four-element vector of the form [x y w h]

Size and location, specified as a four-element vector of the form [x y w h] . The first two elements specify the coordinates of the lower left corner of the text box, rectangle, or ellipse with respect to the lower left corner of the figure. The second two elements specify the width and height of the annotation, respectively.

If you are creating an ellipse, then dim is the size and location of the smallest rectangle that encloses the ellipse.

By default, the units are normalized to the figure. The lower left corner of the figure maps to (0,0) and the upper right corner maps to (1,1) . To change the units, use the Units property

Example: dim = [.3 .4 .5 .6]

container — Target for annotation figure object | uipanel object | uitab object

Target for annotation, specified as a figure, uipanel, or uitab object. For example, to add an annotation to a specific figure, specify the figure object as the first input argument to the function. f = figure; annotation(f, 'line' ,[.1 .2],[.2 .3])

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN , where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: annotation('rectangle',[.5 .5 .1 .1],'EdgeColor','r') creates a rectangle annotation with a red outline.

Each type of annotation object supports a different set of properties. For a full list of properties and descriptions for each type, see the associated property page.

Line Properties

Arrow Properties

DoubleEndArrow Properties

TextArrow Properties

TextBox Properties

Rectangle Properties

Ellipse Properties

Output Arguments

An — annotation object scalar.

Annotation object, returned as a scalar. The type of annotation object returned depends on the first input argument.

Compatibility Considerations

Starting in R2014b, annotations cannot cross uipanel boundaries. Instead, they clip at the boundaries. Previous versions of MATLAB ® allow annotations to extend into (or out of) the boundaries. To display an annotation within a specific figure, uipanel, or uitab, use the container input argument.

Version History

Introduced before R2006a

Abrir ejemplo

Tiene una versión modificada de este ejemplo. ¿Desea abrir este ejemplo con sus modificaciones?

Comando de MATLAB

Ha hecho clic en un enlace que corresponde a este comando de MATLAB:

Ejecute el comando introduciéndolo en la ventana de comandos de MATLAB. Los navegadores web no admiten comandos de MATLAB.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Asia Pacific

Contact your local office

MATLAB Figure Reference: layout.annotations

Sets the horizontal alignment of the `text` within the box. Has an effect only if `text` spans two or more lines (i.e. `text` contains one or more <br> HTML tags) or if an explicit width is set to override the text width.

Sets the color of the annotation arrow.

Sets the end annotation arrow head style.

Sets the annotation arrow head position.

Sets the size of the end annotation arrow head, relative to `arrowwidth`. A value of 1 (default) gives a head about 3x as wide as the line.

Sets the width (in px) of annotation arrow line.

Sets the x component of the arrow tail about the arrow head. If `axref` is `pixel`, a positive (negative) component corresponds to an arrow pointing from right to left (left to right). If `axref` is not `pixel` and is exactly the same as `xref`, this is an absolute value on that axis, like `x`, specified in the same coordinates as `xref`.

Indicates in what coordinates the tail of the annotation (ax,ay) is specified. If set to a x axis id (e.g. 'x' or 'x2'), the `x` position refers to a x coordinate. If set to 'paper', the `x` position refers to the distance from the left of the plotting area in normalized coordinates where '0' ('1') corresponds to the left (right). If set to a x axis ID followed by 'domain' (separated by a space), the position behaves like for 'paper', but refers to the distance in fractions of the domain length from the left of the domain of that axis: e.g., 'x2 domain' refers to the domain of the second x axis and a x position of 0.5 refers to the point between the left and the right of the domain of the second x axis. In order for absolute positioning of the arrow to work, 'axref' must be exactly the same as 'xref', otherwise 'axref' will revert to 'pixel' (explained next). For relative positioning, 'axref' can be set to 'pixel', in which case the 'ax' value is specified in pixels relative to 'x'. Absolute positioning is useful for trendline annotations which should continue to indicate the correct trend when zoomed. Relative positioning is useful for specifying the text offset for an annotated point.

Sets the y component of the arrow tail about the arrow head. If `ayref` is `pixel`, a positive (negative) component corresponds to an arrow pointing from bottom to top (top to bottom). If `ayref` is not `pixel` and is exactly the same as `yref`, this is an absolute value on that axis, like `y`, specified in the same coordinates as `yref`.

Indicates in what coordinates the tail of the annotation (ax,ay) is specified. If set to a y axis id (e.g. 'y' or 'y2'), the `y` position refers to a y coordinate. If set to 'paper', the `y` position refers to the distance from the bottom of the plotting area in normalized coordinates where '0' ('1') corresponds to the bottom (top). If set to a y axis ID followed by 'domain' (separated by a space), the position behaves like for 'paper', but refers to the distance in fractions of the domain length from the bottom of the domain of that axis: e.g., 'y2 domain' refers to the domain of the second y axis and a y position of 0.5 refers to the point between the bottom and the top of the domain of the second y axis. In order for absolute positioning of the arrow to work, 'ayref' must be exactly the same as 'yref', otherwise 'ayref' will revert to 'pixel' (explained next). For relative positioning, 'ayref' can be set to 'pixel', in which case the 'ay' value is specified in pixels relative to 'y'. Absolute positioning is useful for trendline annotations which should continue to indicate the correct trend when zoomed. Relative positioning is useful for specifying the text offset for an annotated point.

Sets the background color of the annotation.

Sets the color of the border enclosing the annotation `text`.

Sets the padding (in px) between the `text` and the enclosing border.

Sets the width (in px) of the border enclosing the annotation `text`.

Determines whether the annotation text box captures mouse move and click events, or allows those events to pass through to data points in the plot that may be behind the annotation. By default `captureevents` is 'false' unless `hovertext` is provided. If you use the event `plotly_clickannotation` without `hovertext` you must explicitly enable `captureevents`.

Makes this annotation respond to clicks on the plot. If you click a data point that exactly matches the `x` and `y` values of this annotation, and it is hidden (visible: false), it will appear. In 'onoff' mode, you must click the same point again to make it disappear, so if you click multiple points, you can show multiple annotations. In 'onout' mode, a click anywhere else in the plot (on another data point or not) will hide this annotation. If you need to show/hide this annotation in response to different `x` or `y` values, you can set `xclick` and/or `yclick`. This is useful for example to label the side of a bar. To label markers though, `standoff` is preferred over `xclick` and `yclick`.

Sets the annotation text font.

HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include 'Arial', 'Balto', 'Courier New', 'Droid Sans',, 'Droid Serif', 'Droid Sans Mono', 'Gravitas One', 'Old Standard TT', 'Open Sans', 'Overpass', 'PT Sans Narrow', 'Raleway', 'Times New Roman'.

Sets an explicit height for the text box. null (default) lets the text set the box height. Taller text will be clipped.

Sets the background color of the hover label. By default uses the annotation's `bgcolor` made opaque, or white if it was transparent.

Sets the border color of the hover label. By default uses either dark grey or white, for maximum contrast with `hoverlabel.bgcolor`.

Sets the hover label text font. By default uses the global hover font and size, with color from `hoverlabel.bordercolor`.

Sets text to appear when hovering over this annotation. If omitted or blank, no hover label will appear.

When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template.

Sets the opacity of the annotation (text + arrow).

Determines whether or not the annotation is drawn with an arrow. If 'true', `text` is placed near the arrow's tail. If 'false', `text` lines up with the `x` and `y` provided.

Sets a distance, in pixels, to move the end arrowhead away from the position it is pointing at, for example to point at the edge of a marker independent of zoom. Note that this shortens the arrow from the `ax` / `ay` vector, in contrast to `xshift` / `yshift` which moves everything by this amount.

Sets the start annotation arrow head style.

Sets the size of the start annotation arrow head, relative to `arrowwidth`. A value of 1 (default) gives a head about 3x as wide as the line.

Sets a distance, in pixels, to move the start arrowhead away from the position it is pointing at, for example to point at the edge of a marker independent of zoom. Note that this shortens the arrow from the `ax` / `ay` vector, in contrast to `xshift` / `yshift` which moves everything by this amount.

Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`.

Sets the text associated with this annotation. Plotly uses a subset of HTML tags to do things like newline (<br>), bold (<b></b>), italics (<i></i>), hyperlinks (<a href='...'></a>). Tags <em>, <sup>, <sub> <span> are also supported.

Sets the angle at which the `text` is drawn with respect to the horizontal.

Sets the vertical alignment of the `text` within the box. Has an effect only if an explicit height is set to override the text height.

Determines whether or not this annotation is visible.

Sets an explicit width for the text box. null (default) lets the text set the box width. Wider text will be clipped. There is no automatic wrapping; use <br> to start a new line.

Sets the annotation's x position. If the axis `type` is 'log', then you must take the log of your desired range. If the axis `type` is 'date', it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is 'category', it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears.

Sets the text box's horizontal position anchor This anchor binds the `x` position to the 'left', 'center' or 'right' of the annotation. For example, if `x` is set to 1, `xref` to 'paper' and `xanchor` to 'right' then the right-most portion of the annotation lines up with the right-most edge of the plotting area. If 'auto', the anchor is equivalent to 'center' for data-referenced annotations or if there is an arrow, whereas for paper-referenced with no arrow, the anchor picked corresponds to the closest side.

Toggle this annotation when clicking a data point whose `x` value is `xclick` rather than the annotation's `x` value.

Sets the annotation's x coordinate axis. If set to a x axis id (e.g. 'x' or 'x2'), the `x` position refers to a x coordinate. If set to 'paper', the `x` position refers to the distance from the left of the plotting area in normalized coordinates where '0' ('1') corresponds to the left (right). If set to a x axis ID followed by 'domain' (separated by a space), the position behaves like for 'paper', but refers to the distance in fractions of the domain length from the left of the domain of that axis: e.g., 'x2 domain' refers to the domain of the second x axis and a x position of 0.5 refers to the point between the left and the right of the domain of the second x axis.

Shifts the position of the whole annotation and arrow to the right (positive) or left (negative) by this many pixels.

Sets the annotation's y position. If the axis `type` is 'log', then you must take the log of your desired range. If the axis `type` is 'date', it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is 'category', it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears.

Sets the text box's vertical position anchor This anchor binds the `y` position to the 'top', 'middle' or 'bottom' of the annotation. For example, if `y` is set to 1, `yref` to 'paper' and `yanchor` to 'top' then the top-most portion of the annotation lines up with the top-most edge of the plotting area. If 'auto', the anchor is equivalent to 'middle' for data-referenced annotations or if there is an arrow, whereas for paper-referenced with no arrow, the anchor picked corresponds to the closest side.

Toggle this annotation when clicking a data point whose `y` value is `yclick` rather than the annotation's `y` value.

Sets the annotation's y coordinate axis. If set to a y axis id (e.g. 'y' or 'y2'), the `y` position refers to a y coordinate. If set to 'paper', the `y` position refers to the distance from the bottom of the plotting area in normalized coordinates where '0' ('1') corresponds to the bottom (top). If set to a y axis ID followed by 'domain' (separated by a space), the position behaves like for 'paper', but refers to the distance in fractions of the domain length from the bottom of the domain of that axis: e.g., 'y2 domain' refers to the domain of the second y axis and a y position of 0.5 refers to the point between the bottom and the top of the domain of the second y axis.

Shifts the position of the whole annotation and arrow up (positive) or down (negative) by this many pixels.

Hilfebereich Hilfebereich

Labels and Annotations

Add a title, label the axes, or add annotations to a graph to help convey important information. You can create a legend to label plotted data series or add descriptive text next to data points. Also, you can create annotations such as rectangles, ellipses, arrows, vertical lines, or horizontal lines that highlight specific areas of data.

alle erweitern

Annotations

Eigenschaften.

This example shows how to add a title and axis labels to a chart by using the title , xlabel , and ylabel functions.

Modify the font size and length of graph titles.

Label data series using a legend and customize the legend appearance such as changing the location, setting the font size, or using multiple columns.

This example shows how to add text to a chart, control the text position and size, and create multiline text.

You can add text to a chart that includes Greek letters and special characters using TeX markup.

Annotations are extra information added to a chart to help identify important information.

MATLAB-Befehl

Sie haben auf einen Link geklickt, der diesem MATLAB-Befehl entspricht:

Führen Sie den Befehl durch Eingabe in das MATLAB-Befehlsfenster aus. Webbrowser unterstützen keine MATLAB-Befehle.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Asia Pacific

Contact your local office

Centro assistenza Centro assistenza

Labels and Annotations

Add a title, label the axes, or add annotations to a graph to help convey important information. You can create a legend to label plotted data series or add descriptive text next to data points. Also, you can create annotations such as rectangles, ellipses, arrows, vertical lines, or horizontal lines that highlight specific areas of data.

espandi tutto

Annotations

This example shows how to add a title and axis labels to a chart by using the title , xlabel , and ylabel functions.

Modify the font size and length of graph titles.

Label data series using a legend and customize the legend appearance such as changing the location, setting the font size, or using multiple columns.

This example shows how to add text to a chart, control the text position and size, and create multiline text.

You can add text to a chart that includes Greek letters and special characters using TeX markup.

Annotations are extra information added to a chart to help identify important information.

Comando MATLAB

Hai fatto clic su un collegamento che corrisponde a questo comando MATLAB:

Esegui il comando inserendolo nella finestra di comando MATLAB. I browser web non supportano i comandi MATLAB.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Asia Pacific

Contact your local office

Help Center Help Center

Add Text to Chart

This example shows how to add text to a chart, control the text position and size, and create multiline text.

Text Position

Add text next to a particular data point using the text function. In this case, add text to the point ( π , sin ( π ) ) . The first two input arguments to the text function specify the position. The third argument specifies the text.

By default, text supports a subset of TeX markup. Use the TeX markup \pi for the Greek letter π . Display an arrow pointing to the left by including the TeX markup \leftarrow . For a full list of markup, see Greek Letters and Special Characters in Chart Text .

Figure contains an axes object. The axes object contains 2 objects of type line, text.

Text Alignment

By default, the specified data point is to the left of the text. Align the data point to the right of the text by specifying the HorizontalAlignment property as 'right' . Use an arrow pointing to the right instead of to the left.

Figure contains an axes object. The axes object contains 2 objects of type line, text.

Specify the font size for text by setting the FontSize property as a name-value pair argument to the text function. You can use a similar approach to change the font size when using the title , xlabel , ylabel , or legend functions.

Figure contains an axes object. The axes object contains 2 objects of type line, text.

Alternatively, starting in R2022a, you can change the font size of the axes text by using the fontsize function.

Setting Text Properties

The text function creates a Text object. Text objects have properties that you can use to customize the appearance of the text, such as the HorizontalAlignment or FontSize .

You can set properties in two ways:

Use name-value pairs in the text command, such as 'FontSize',14 .

Use the Text object. You can return the Text object as an output argument from the text function and assign it to a variable, such as t . Then, use dot notation to set properties, such as t.FontSize = 14 .

For this example, change the font size using dot notation instead of a name-value pair.

Figure contains an axes object. The axes object contains 2 objects of type line, text.

Multiline Text

Display text across multiple lines using a cell array of character vectors. Each element of the cell array is one line of text. For this example, display a title with two lines. You can use a similar approach to display multiline text with the title , xlabel , ylabel , or legend functions.

Figure contains an axes object. The axes object contains 2 objects of type line, text.

Text with Variable Value

Include a variable value in text by using the num2str function to convert the number to text. For this example, calculate the average y value and include the value in the title. You can use a similar approach to include variable values with the title , xlabel , ylabel , or legend functions.

Figure contains an axes object. The axes object contains 2 objects of type line, text.

Text Outside Axes

Add text anywhere within the figure using the annotation function instead of the text function. The first input argument specifies the type of annotation. The second input argument specifies the position of the annotation in units normalized to the figure. Remove the text box border by setting the EdgeColor property to 'none' . For more information on text box annotations, see the annotation function.

Figure contains an axes object. The axes object contains an object of type line.

text | title | xlabel | ylabel | annotation | fontsize

Related Topics

Ouvrir l'exemple

Vous possédez une version modifiée de cet exemple. Souhaitez-vous ouvrir cet exemple avec vos modifications ?

Commande MATLAB

Vous avez cliqué sur un lien qui correspond à cette commande MATLAB :

Pour exécuter la commande, saisissez-la dans la fenêtre de commande de MATLAB. Les navigateurs web ne supportent pas les commandes MATLAB.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Asia Pacific

Contact your local office

Matlab and Simulink Tutorials

Matlab Simulink Examples

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

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

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.

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.

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

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.

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.

Editing Text Objects

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.

[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:

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.

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.

For example,

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 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,

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

The three separate strings concatenate into one.

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

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.

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:

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.

Tags: and TEX Characters annotation array arrays BackgroundColor bar block cat cell Cell Arrays char Command Window commands computer curve diag differential disp double EdgeColor edit Editor Enable end eps example Examples exp Expression Extent figure find for format function Functions get graph Greek Letters gtext Handle HorizontalAlignment if inf Interpreter Latex line LineStyle LineWidth Margin mat Mathematical Mathematical Expression Mathematical Symbols matlab matrix max maximum min mode model more Name num2str order peaks Plot Edit Mode plotedit plotting Position Positioning Annotations in Data Space properties property editor rectangle reference rem set sim Simulate sin size special characters statements string struct subset Support Symbols table of available TEX text Text Alignment Text in Cell Arrays The Property Editor Toolbar uicontrol Units VerticalAlignment view warning what where zlabel

You may also like...

matlab

Class Definition-Syntax Reference & Specifying Properties

April 18, 2010

 by admin · Published April 18, 2010 · Last modified July 25, 2020

Polynomials in Matlab

February 14, 2021

 by Matlab · Published February 14, 2021

annotation text plot matlab

Wireless Engineering with Matlab

February 11, 2020

 by admin · Published February 11, 2020 · Last modified June 5, 2020

Popular Post

What Is Model-Based Design? Matlab Modeling Process

The find Function

Managing Desktop Layouts

Programming and Scripts

Syntax Reference & Specifying Attributes

Logical Subscripting

Using .NET from MATLAB

Analysis of Functions, Interpolation, Curve Fitting, Integrals and Differential Equations

Notebook Feature Reference

Examples of Expressions

Constructing Sparse Matrices

Analysis of Functions, Interpolation, Curve Fitting, Integrals and Differential Equations 2

Calling Superclass Methods on Subclass Objects

Scoping Classes with Packages

Implementing a Set/Get Interface for Properties

Displaying Graphics Images

Using the Editor and Debugger with Classes

Stream Line Plots of Vector Data

Matlab Plot Objects

Matlab GUIDE: Getting Started

MATLAB GUI (Graphical User Interface) Tutorial for Beginners

Marking Up Graphs with Data Brushing

Simulink Building the Model

Simulation of a Bouncing Ball

Matlab Class Overview

Matlab Class for Graphing Functions

Matlab Tutorials

array case cat char class classes dir disp edit end example Examples exp for format function Functions get graph graphic Handle if inf line load mat matlab matlab functions matrix method methods min more Name open properties reference rem return set sim sin size text where

Matlab Articles

Matlab Annotation Objects and Example

Linear Algebra

Plotting Tools — Interactive Plotting

Finding maximum and minimum values in arrays

Privacy Overview

IMAGES

  1. annotations

    annotation text plot matlab

  2. Create annotations

    annotation text plot matlab

  3. how can I add a box in MATLAB figure which will show average values of

    annotation text plot matlab

  4. Matlab Annotation

    annotation text plot matlab

  5. Pinning annotations to graphs

    annotation text plot matlab

  6. Annotation Text Size Doesn't Change on MATLAB Plot

    annotation text plot matlab

VIDEO

  1. Pengenalan Toolbar Annotation (Text & Dimension)

  2. LabVIEW: Adding annotation to graph

  3. 03 matlab plot objects hierarchy

  4. MATLAB BASIC 24

  5. Affordable Independent house

  6. Annotating Plots, Demonstration

COMMENTS

  1. Create annotations

    Description example annotation (lineType,x,y) creates a line or arrow annotation extending between two points in the current figure. Specify lineType as 'line', 'arrow', 'doublearrow' , or 'textarrow'. Specify x and y as two-element vectors of the form [x_begin x_end] and [y_begin y_end], respectively.

  2. Add Annotations to Chart

    Use the annotation function to add annotations to a chart. The first input to the function specifies the type of annotation you want to create. If you specify the type as 'line', 'arrow', 'doublearrow', or 'textarrow', then the second input is the starting and ending x positions of the annotation.

  3. annotation in matlab plot

    annotation in matlab plot Ask Question Asked 13 years, 2 months ago Modified 6 years, 10 months ago Viewed 19k times 6 I just wonder how to add annotation in matlab plot? Here is my code: plot (x,y); annotation ('textarrow', [x, x+0.05], [y,y+0.05],'String','my point','FontSize',14); But the arrow points to the wrong place. How can I fix it?

  4. Text and annotations in MATLAB

    How to make Text and Annotations plots in MATLAB ® with Plotly. Adding Text to Plots with the text Function x = -pi:pi/10:pi; y = sin(x); figure('Name', 'Sample graph'), plot(x, y, '--rs'); for i=8:size(x,2)-8 text(x(i), y(i), 'Text'); end fig2plotly(gcf);

  5. Create annotations

    Create a simple line plot and add a text box annotation to the figure. ... Instead, they clip at the boundaries. Previous versions of MATLAB ® allow annotations to extend into (or out of) the boundaries. To display an annotation within a specific figure, uipanel, or uitab, use the container input argument. Version History.

  6. Layout.annotations in MATLAB

    layout.annotations. Type: cell array of struct where each struct has one or more of the keys listed below. An annotation is a text element that can be placed anywhere in the plot. It can be positioned with respect to relative coordinates in the plot or with respect to the actual data coordinates of the graph.

  7. Labels and Annotations

    Labels and Annotations. Add titles, axis labels, informative text, and other graph annotations. Add a title, label the axes, or add annotations to a graph to help convey important information. You can create a legend to label plotted data series or add descriptive text next to data points. Also, you can create annotations such as rectangles ...

  8. Labels and Annotations

    Labels and Annotations. Add titles, axis labels, informative text, and other graph annotations. Add a title, label the axes, or add annotations to a graph to help convey important information. You can create a legend to label plotted data series or add descriptive text next to data points. Also, you can create annotations such as rectangles ...

  9. Add Text to Chart

    Add text next to a particular data point using the text function. In this case, add text to the point ( π, sin ( π)). The first two input arguments to the text function specify the position. The third argument specifies the text. By default, text supports a subset of TeX markup. Use the TeX markup \pi for the Greek letter π.

  10. Adding Text Annotations to Graphs

    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.