Как изменить размер шрифта matlab

Change the zoom level, font size, name, and style used by tools in MATLAB such as the Editor and Command Window.

You can change the zoom level, font size, name, and style used by tools in MATLAB®. You also can install new fonts to use with
MATLAB.

Zoom

You can change the zoom level in the Editor, Live Editor, and Help browser. To
zoom in and out, hold the Ctrl key and move the scroll wheel. On
macOS systems, use the Command key instead.

Alternatively, you can zoom in and out using the available keyboard
shortcuts.

Action Keyboard Shortcut

Zoom in

Ctrl+Plus

On macOS systems, use
Command+Shift+Plus.

Zoom out

Ctrl+Minus

On macOS systems, use
Command+Shift+Minus.

Reset Zoom

(Not supported in Help
browser)

Ctrl+Alt+0

On macOS systems, use
Command+Alt+0.

Alternatively, you can change the zoom level in the Editor and Live Editor by
going to the View tab and selecting
Zoom In,
Zoom Out, or
Reset Zoom.

In MATLAB
Online™
, to change the zoom level, adjust the zoom settings for your web
browser.

Change Font Size

You can change the font size in MATLAB using preferences or settings. This table describes how to change the font size
for each tool.

Tool Procedure

Live Editor

Specify the font size for code and text programmatically
using settings. For example, this code changes the code font
size in the Live
Editor.

s = settings;
s.matlab.fonts.editor.code.Size.TemporaryValue = '26pt'

For
more information, see matlab.fonts Settings.

Code tools

  • Editor

  • Command Window

  • Command History

Specify the font size using font
preferences.

On the Home tab, in the Environment section, click

Preferences. Select > and, in the Desktop code font
section, select a font size.

Text-based tools

  • Current Folder browser

  • Workspace browser

  • Variables editor

Specify the font size using font
preferences.

On the Home tab, in the Environment section, click

Preferences. Select > and in the Desktop text font
section, clear the Use system font check
box. Then, select a font size.

Charts

See Add Title and Axis Labels to Chart.

In MATLAB
Online
, you only can change the font size for the Editor, Command Window, and
Live Editor.

Change Font Name and Style

You can change the font name and style in MATLAB using several different methods,
depending on the tool. This table describes how to change the font name and style
for each tool in MATLAB.

Tool Procedure

Live Editor

Specify the font name and style for code and text
programmatically using settings. For example, this code changes
the font name and style of normal text in the Live
Editor.

s = settings;
s.matlab.fonts.editor.normal.Name.PersonalValue = 'Calibri';
s.matlab.fonts.editor.normal.Style.PersonalValue = {'bold'};

For
more information, see matlab.fonts Settings.

Code tools

  • Editor

  • Command Window

  • Command History

Specify the font name and style using font
preferences.

On the Home tab, in the Environment section, click

Preferences. Select > and, in the Desktop code font
section, select a font name and style.

By default,
the code font is set to monospaced to preserve vertical
alignment. When the font is set to monospaced, the actual
displayed font in the Editor is different than the font
displayed in the Command Window and Command History. This is
because monospaced is a logical font, not a physical font. To
avoid this discrepancy, specify the font name as a physical
font, for example, Courier
New
.

Text-based tools

  • Current Folder browser

  • Workspace browser

  • Variables editor

Specify the font name and style using font
preferences.

On the Home tab, in the Environment section, click

Preferences. Select > and, in the Desktop text font
section, clear the Use system font check
box. Then, select a font name and style. By default, the text
font is set to your system font.

Help Browser

MATLAB web browser

Changing the font name and style is not
supported.

In MATLAB
Online
, you only can change the font name and font style for the Editor,
Command Window, and Live Editor.

To apply antialiasing and create a smoother desktop appearance on Linux® systems, select Use antialiasing to smooth desktop
fonts
. You must restart MATLAB for the preference to take effect. On Microsoft®
Windows® and macOS platforms, MATLAB uses system setting for antialiasing.

Advanced Customization

You can further customize fonts in MATLAB by changing the font preferences for an individual tool. To change the
font preferences, on the Home tab, in the Environment section, click
Preferences. Select > > and choose a tool from the list of Desktop tools.
Then, select the font to use:

  • Desktop code — Select this option to use the
    desktop code font for this tool.

  • Desktop text — Select this option to use the
    desktop text font for this tool.

  • Custom — Select this option to specify a
    custom font for this tool. Then, specify a font name, style, and size. Some
    options are not supported for all tools.

For example, to change the Editor font to a custom font, in the list of
Desktop tools, select Editor. Then, in
the Font to use section, select Custom and
specify the desired font name, style, and size.

Setting custom font preferences is not supported for the Live Editor. To change
the font name and style of code and text in the Live Editor, use settings. For more
information, see matlab.fonts Settings. In
MATLAB
Online
, setting custom font preferences is only supported for the Editor and
Command Window.

Default Font Preferences

This table shows the default font preferences for the tools in MATLAB. You can use this table to restore fonts to their original
state.

Tool

Font to Use

Default Font

Command History

Desktop
code

Monospaced, plain, 10
point

When the font is set to monospaced, the
actual displayed font in the Editor is different than the
font displayed in the Command Window and Command History.
This is because monospaced is a logical font, not a physical
font. To avoid this discrepancy, specify the font name as a
physical font, for example, Courier
New
.

Command Window

Editor (and Shortcuts Editor)

Current Folder browser (and Path
browser)

Desktop
text

Your system’s current font

Workspace browser

Variables editor

Function Browser

Profiler

Custom

Sans serif, plain, 10 point

Add New Font

You can install new fonts to use with MATLAB. A common reason to install additional fonts is to read files created
in different languages. For details on adding fonts to your system, refer to the
documentation for your system.

Choose a new font that is compatible with MATLAB. MATLAB only includes compatible fonts in the font preferences.

  • For desktop components (such as the Command Window), figure windows, and
    uicontrols, fonts must be compatible with TrueType and Microsoft
    OpenType® fonts

  • For graphics objects, such as xlabel,
    ylabel, title, and
    text, fonts must be TrueType and Microsoft
    OpenType fonts

Install your new font in a location where MATLAB looks for fonts. MATLAB looks for fonts in these locations:

  • The operating system’s standard location (see your system administrator
    for details)

  • The /jre/lib/fonts folder where Java® software is installed on your system

If you install a font with MATLAB running, restart MATLAB to include the font in the font preferences.

Then, to use the new font, follow the instructions in Change Font Name and Style.

See Also

Preferences

Related Topics

  • Add Title and Axis Labels to Chart
  • Change Desktop Colors
  • Set Print Options for Command Window and Editor

fontsize

Change font size for objects in a figure

Syntax

Description

example

fontsize(obj,size,units)
sets the font size and font units for all of the text within graphics object
obj. If obj contains other graphics objects, such as
a figure that contains UI components or an axes object that has a legend,
fontsize also sets the font size and font units for those objects
within obj. Font units can be "points",
"pixels", "inches", or
"centimeters".

example

fontsize(obj,"increase")
increases the font size by a factor of 1.1.

fontsize(obj,"decrease")
decreases the font size by a factor of 0.9.

example

fontsize(obj,scale=sfactor)
scales the font size by a factor of sfactor. For example, use a scale
factor of 1.2 to scale by 120%.

example

fontsize(obj,"default")
resets the font size and font units back to the default, automatic values for
obj.

Examples

collapse all

Change Font Size of Plot Text

Create a plot of random data, and add a plot title and legend.

y = rand(5);
plot(y)
title("2-D Line Plot")
legend("Line 1","Line 2","Line 3","Line 4","Line 5")

Figure contains an axes object. The axes object with title 2-D Line Plot contains 5 objects of type line. These objects represent Line 1, Line 2, Line 3, Line 4, Line 5.

Set the font size of all text within the axes object to 10 and the font units to "pixels". Use the object returned by gca as the target object to apply this change.

fontsize(gca,10,"pixels")

Figure contains an axes object. The axes object with title 2-D Line Plot contains 5 objects of type line. These objects represent Line 1, Line 2, Line 3, Line 4, Line 5.

Scale Font Size of Text in Figure

Create a plot with several text elements of varying font sizes.

[X,Y,Z] = peaks;
contourf(X,Y,Z,LineColor="#4F4F4F")
title("Peak Elevation")
colorbar
annotation("textarrow",[.53 .41],[.65 .47],String="Local maxima")
annotation("textarrow",[.53 .59],[.65 .55])

Figure contains an axes object. The axes object with title Peak Elevation contains an object of type contour.

Scale the font sizes in the figure by 120% by using a scale factor of 1.2. The fontsize function scales each font size individually, maintaining the relative sizes of the fonts.

Figure contains an axes object. The axes object with title Peak Elevation contains an object of type contour.

Change Font Size in Tiled Chart Layout

Create a tiling of several plots by using the tiledlayout and nexttile functions.

x = linspace(0,3*pi,200);
y = cos(x) + rand(1,200);
t = tiledlayout(2,2);

% Top scatter plot in tiles 1,2
ax1 = nexttile([1 2]);
scatter(x,y)
title("Random Variance on Cosine")

% Lower polar plot in tile 3
ax2 = nexttile;
plot(x,cos(x)+0.5)

% Lower histogram in tile 4
ax3 = nexttile;
histogram(y,20)

Figure contains 3 axes objects. Axes object 1 with title Random Variance on Cosine contains an object of type scatter. Axes object 2 contains an object of type line. Axes object 3 contains an object of type histogram.

Scale up the font size of the scatter plot, and change the font size of the other two plots to 10 pixels.

fontsize(ax1,scale=1.2)
fontsize([ax2 ax3],10,"pixels")

Figure contains 3 axes objects. Axes object 1 with title Random Variance on Cosine contains an object of type scatter. Axes object 2 contains an object of type line. Axes object 3 contains an object of type histogram.

To undo the font size changes across all the tiled plots, reset the font sizes and units to their default values. Apply this change to all three plots by using the current figure object returned by gcf.

Figure contains 3 axes objects. Axes object 1 with title Random Variance on Cosine contains an object of type scatter. Axes object 2 contains an object of type line. Axes object 3 contains an object of type histogram.

Change Font Size of App Text

Create the following function file, and save it as myapplayout.m on your MATLAB® path. This function returns the layout for a simple app to plot data using different plot types.

function fig = myapplayout
% Create figure window
fig = uifigure;

% Create UI components
ax = uiaxes(fig,Position=[15 70 535 340]);
lbl = uilabel(fig,Position=[30 15 100 35],Text="Choose Plot Type:");
b1 = uibutton(fig,Position=[140 15 180 35],Text="Surf");
b2 = uibutton(fig,Position=[350 15 180 35],Text="Mesh");

% Configure UI component appearance
surf(ax,peaks);
fontsize(fig,8,"pixels")
title(ax,"Peak Surface",FontSize=11)
end

Call the function and assign the returned figure object to f.

{"String":"Figure contains an axes object and other objects of type uilabel, uibutton. The axes object with title Peak Surface contains an object of type surface.","Tex":"Peak Surface","LaTex":[]}

Use f to increase the font size of all text in the figure until it is more easily readable. Here, the fontsize function increases each font size individually by a scale factor of 1.1, maintaining the relative sizes of the fonts.

fontsize(f,"increase")
fontsize(f,"increase")
fontsize(f,"increase")

{"String":"Figure contains an axes object and other objects of type uilabel, uibutton. The axes object with title Peak Surface contains an object of type surface.","Tex":"Peak Surface","LaTex":[]}

Input Arguments

collapse all

objObject or container with text
graphics object | array of graphics objects

Object or container with text, specified as a graphics object or array of graphics
objects. The fontsize function sets the font size of text in the
specified objects. If obj contains other graphics objects, such as a
figure that contains UI components or an axes object that has a legend, the function
also sets the font size and font units for those objects within obj.
Objects without a FontSize property are not affected.

sizeFont size
positive scalar value

Font size, specified as a positive scalar value.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

unitsFont size units
"points" | "pixels" | "inches" | "centimeters"

Font size units, specified as "points",
"pixels", "inches", or
"centimeters".

sfactorScale factor
scalar

Scale factor, specified as a scalar. All font sizes under the target object are
scaled by sfactor. Use a scale factor greater than
1 to increase the font sizes or a factor less than
1 to decrease the font sizes.

Example: fontsize(gcf,scale=0.8) scales the text to 80% of its
original size.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Version History

Introduced in R2022a

Изменение шрифтов

Измените размер шрифта

Изменение размера шрифта в MATLAB® зависит от инструмента. Эта таблица описывает, как изменить размер шрифта для каждого инструмента в MATLAB.

Чтобы изменить размер шрифта для графиков, смотрите Добавление заголовка и подписей по осям, чтобы Строить диаграмму.

Инструмент Процедура

Live Editor

Используйте горячие клавиши Ctrl + Minus (-) и Ctrl + Plus (+).

Инструменты кода

  • Редактор

  • Командное окно

  • История команд

На вкладке «Главная страница (Home)» в разделе «Конфигурация (Environment)» нажмите «Настройки (Preferences)».
Выберите > и в разделе Desktop code font, выберите размер шрифта.

Основанные на тексте инструменты

  • Браузер текущей папки

  • Браузер рабочей области

  • Редактор переменных

На вкладке «Главная страница (Home)» в разделе «Конфигурация (Environment)» нажмите «Настройки (Preferences)».
Выберите > и в разделе Desktop text font, очистите опцию Use system font. Затем выберите размер шрифта.

Браузер документации

Веб-браузер MATLAB

Используйте горячие клавиши Ctrl + Minus (-) и Ctrl + Plus (+).

В MATLAB Online™ только можно изменить размер шрифта для Редактора.

Измените название шрифта и стиль

Изменение названия шрифта и стиля в MATLAB зависит от инструмента. Эта таблица описывает, как изменить название шрифта и стиль для каждого инструмента в MATLAB.

Инструмент Процедура

Live Editor

Изменение названия шрифта и стиля не поддерживается.

Инструменты кода

  • Редактор

  • Командное окно

  • История команд

На вкладке «Главная страница (Home)» в разделе «Конфигурация (Environment)» нажмите «Настройки (Preferences)».
Выберите > и в разделе Desktop code font, выберите название шрифта и стиль. По умолчанию шрифт кода установлен моноширинный, чтобы сохранить выравнивание по вертикали.

Основанные на тексте инструменты

  • Браузер текущей папки

  • Браузер рабочей области

  • Редактор переменных

На вкладке «Главная страница (Home)» в разделе «Конфигурация (Environment)» нажмите «Настройки (Preferences)».
Выберите > и в разделе Desktop text font, очистите опцию Use system font. Затем выберите название шрифта и стиль. По умолчанию шрифт текста установлен в ваш системный шрифт.

Браузер документации

Веб-браузер MATLAB

Изменение названия шрифта и стиля не поддерживается.

В MATLAB Online только можно изменить название шрифта и стиль для Редактора.

Чтобы применить сглаживание и создать более сглаженную настольную видимость в системах UNIX®, выберите Use antialiasing to smooth desktop fonts. Необходимо перезапустить MATLAB для настройки, чтобы вступить в силу. На Microsoft® Windows® и платформах Macintosh, MATLAB использует параметр настройки системы для сглаживания.

Усовершенствованная индивидуальная настройка

Можно далее настроить шрифты в MATLAB путем изменения настроек шрифта для отдельного инструмента. На вкладке «Главная страница (Home)» в разделе «Конфигурация (Environment)» нажмите «Настройки (Preferences)».
Выберите > > . Затем выберите инструмент из списка Desktop tools и задайте Font to use:

  • Desktop code — Задайте эту опцию, чтобы использовать настольный шрифт кода для этого инструмента.

  • Desktop text — Задайте эту опцию, чтобы использовать системный шрифт для этого инструмента.

  • Custom — Задайте эту опцию, чтобы задать пользовательский шрифт для этого инструмента. Затем задайте название шрифта, стиль и размер.

Например, чтобы изменить шрифт Редактора в пользовательский шрифт, в списке Desktop tools, выбирают Editor. Затем в разделе Font to use выберите Custom и задайте желаемое название шрифта, стиль и размер.

Некоторые инструменты, такие как Профилировщик, используют пользовательский шрифт по умолчанию.

Примечание

Для Профилировщика можно изменить тип шрифта и размер, но не стиль (например, полужирный или курсивный).

Эта таблица показывает настройки стандартного шрифта для инструментов в MATLAB. Используйте эту таблицу, чтобы восстановить шрифты к их исходному состоянию.

Инструмент

Шрифт, чтобы использовать

Стандартный шрифт

История команд

Desktop code

Моноширинный, Простой, 10 точек

Командное окно

Редактор (и редактор ярлыков)

Браузер текущей папки (и браузер Пути)

Desktop text

Текущий шрифт вашей системы

Браузер рабочей области

Редактор переменных

Браузер функций

Профилировщик

Custom

SansSerif, Плоскость, 10 точек

Добавление шрифтов

MATLAB определяет набор шрифты, используемые в настройках шрифта от шрифтов, установленных в вашей системе. MATLAB ищет шрифты в этих местоположениях:

  • Стандартное местоположение операционной системы (см. своего системного администратора для деталей),

  • /jre/lib/fonts папка, где программное обеспечение Java® установлено в вашей системе

MATLAB только включает совместимые шрифты в настройки шрифта.

  • Для настольных компонентов (таких как Командное окно), окна рисунка и uicontrol, шрифты должны быть совместимы со шрифтами Microsoft OpenType® и TrueType

  • Для графических объектов, таких как xlabelYLabel заголовок, и text, шрифты должны быть шрифты Microsoft OpenType и TrueType

Если вы устанавливаете шрифт с выполнением MATLAB, перезапускаете MATLAB, чтобы включать шрифт в настройки шрифта. Общая причина установить дополнительные шрифты состоит в том, чтобы считать файлы, созданные на различных языках. Для получения дополнительной информации на добавляющих шрифтах к вашей системе, обратитесь к документации для своей системы.

Похожие темы

  • Установка опций печати
  • Добавление заголовка и подписей по осям, чтобы строить диаграмму

TextBox Properties

Text box appearance and behavior

TextBox properties control the appearance
and behavior of a TextBox object. By changing property
values, you can modify certain aspects of the text box. Use dot notation to query and
set properties.

t = annotation('textbox');
sz = t.FontSize;
t.FontSize = 12;

expand all

Text to display, specified as a character vector, cell array of character vectors,
string array, categorical array, or numeric value. Specify a value according to how you
want the text to appear. This table lists the most common situations.

Appearance of Text Description of Value Example
One line of text Character vector or 1-by-1 string array.
str = 'My Text'

or

str = "My Text"
Multiple lines of text Cell array of character vectors or a string array.
str = {'First line','Second line'};

or

str = ["First line", "Second line"];
Text that includes a numeric variable Array that includes the number converted to a
char array. Use num2str to convert
the value.
x = 42;
str = ['The value is ',num2str(x)];
Text that includes special characters such as Greek letters or
mathematical symbols
Array that includes TeX markup. For a list of supported markup,
see the Interpreter property.
str = 'x ranges from 0 to 2pi'

Note

  • The words default, factory, and
    remove are reserved words that do not appear in text
    when quoted as normal characters. To display any of these words
    individually, precede them with a backslash, such as
    'default' or 'remove'.

  • If you specify this property as a categorical array, MATLAB® uses the values in the array, not the categories.

  • If you specify text that contains only a numeric value, the value is
    converted using sprintf('%g',value). For example,
    12345678 displays as
    1.23457e+07.

Text color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short
name. The default value of [0 0 0] corresponds to black.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0
0 1]

Example: '#0000FF'

Text interpreter, specified as one of these values:

  • 'tex' — Interpret characters using a subset of
    TeX markup.

  • 'latex' — Interpret characters using LaTeX
    markup.

  • 'none' — Display literal characters.

TeX Markup

By default, MATLAB supports a subset of TeX markup. Use TeX markup to add superscripts
and subscripts, modify the font type and color, and include special characters in
the text.

Modifiers remain in effect until the end of the text.
Superscripts and subscripts are an exception because they modify only the next character or the
characters within the curly braces. When you set the interpreter to 'tex',
the supported modifiers are as follows.

Modifier Description Example
^{ } Superscript 'text^{superscript}'
_{ } Subscript 'text_{subscript}'
bf Bold font 'bf text'
it Italic font 'it text'
sl Oblique font (usually the same as italic font) 'sl text'
rm Normal font 'rm text'
fontname{specifier} Font name — Replace
specifier with the name of
a font family. You can use this in combination with other modifiers.
'fontname{Courier} text'
fontsize{specifier} Font size —Replace
specifier with a numeric
scalar value in point units.
'fontsize{15} text'
color{specifier} Font color — Replace
specifier with one of
these colors: red, green,
yellow, magenta,
blue, black,
white, gray,
darkGreen, orange, or
lightBlue.
'color{magenta} text'
color[rgb]{specifier} Custom font color — Replace
specifier with a
three-element RGB triplet.
'color[rgb]{0,0.5,0.5} text'

This table lists the supported special characters for the
'tex' interpreter.

Character Sequence Symbol Character Sequence Symbol Character Sequence Symbol

alpha

α

upsilon

υ

sim

~

angle

phi

ϕ

leq

ast

*

chi

χ

infty

beta

β

psi

ψ

clubsuit

gamma

γ

omega

ω

diamondsuit

delta

δ

Gamma

Γ

heartsuit

epsilon

ϵ

Delta

Δ

spadesuit

zeta

ζ

Theta

Θ

leftrightarrow

eta

η

Lambda

Λ

leftarrow

theta

θ

Xi

Ξ

Leftarrow

vartheta

ϑ

Pi

Π

uparrow

iota

ι

Sigma

Σ

rightarrow

kappa

κ

Upsilon

ϒ

Rightarrow

lambda

λ

Phi

Φ

downarrow

mu

µ

Psi

Ψ

circ

º

nu

ν

Omega

Ω

pm

±

xi

ξ

forall

geq

pi

π

exists

propto

rho

ρ

ni

partial

sigma

σ

cong

bullet

varsigma

ς

approx

div

÷

tau

τ

Re

neq

equiv

oplus

aleph

Im

cup

wp

otimes

subseteq

oslash

cap

in

supseteq

supset

lceil

subset

int

cdot

·

o

ο

rfloor

neg

¬

nabla

lfloor

times

x

ldots

perp

surd

prime

´

wedge

varpi

ϖ

rceil

rangle

mid

|

vee

langle

copyright

©

LaTeX Markup

To use LaTeX markup, set the interpreter to 'latex'. For inline
mode, surround the markup with single dollar signs ($). For
display mode, surround the markup with double dollar signs
($$).

LaTeX Mode Example Result
Inline
'$int_1^{20} x^2 dx$'

Equation with LaTeX inline mode

Display
'$$int_1^{20} x^2 dx$$'

Equation with LaTeX display mode

The displayed text uses the default LaTeX font style. The
FontName, FontWeight, and
FontAngle properties do not have an effect. To change the
font style, use LaTeX markup.

The maximum size of the text that you can use with the LaTeX interpreter is 1200
characters. For multiline text, this reduces by about 10 characters per line.

For examples that use TeX and LaTeX, see Greek Letters and Special Characters in Chart Text. For more information about the LaTeX
system, see The LaTeX Project website at https://www.latex-project.org/.

Font

expand all

Font name, specified as a supported font name or 'FixedWidth'. To display
and print text properly, you must choose a font that your system supports. The default
font depends on your operating system and locale.

To use a fixed-width font that looks good in any locale, use 'FixedWidth'.
The fixed-width font relies on the root FixedWidthFontName
property. Setting the root FixedWidthFontName property causes an
immediate update of the display to use the new font.

Font size, specified as a scalar value greater than 0 in point units. The default font size
depends on the specific operating system and locale. One point equals 1/72 inch. To
change the font units, use the FontUnits property.

Example: 12

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical

Character thickness, specified as 'normal' or
'bold'.

MATLAB uses the FontWeight property to select a font from
those available on your system. Not all fonts have a bold weight. Therefore, specifying
a bold font weight can still result in the normal font weight.

Character slant, specified as 'normal' or
'italic'.

Not all fonts have both font styles. Therefore, the italic font might look the same
as the normal font.

FontUnitsFont size units
'points' (default) | 'inches' | 'centimeters' | 'normalized' | 'pixels'

Font size units, specified as one of the values in this
table.

Units Description
'points' Points. One point equals 1/72 inch.
'inches' Inches.
'centimeters' Centimeters.
'normalized' Interpret font size as a fraction of the parent
container height, typically a figure. If you resize the
container, the font size modifies accordingly. For
example, if the FontSize is
0.1 in normalized units, then the
text is 1/10 of the container height.
'pixels'

Pixels.

Starting in R2015b, distances in pixels are
independent of your system resolution on Windows® and Macintosh systems:

  • On Windows systems, a pixel is 1/96th of an
    inch.

  • On Macintosh systems, a pixel is 1/72nd of an
    inch.

On Linux® systems, the size of a pixel is
determined by your system resolution.

If you set both the font size and the font units in one function call, you
must set the FontUnits property first so that the axes
correctly interprets the specified font size.

Text Box

expand all

FitBoxToTextOption to fit box width and height to text
'on' (default) | on/off logical value

Option to fit the box width and height to the text, specified as
'on' or 'off', or as numeric or
logical 1 (true) or
0 (false). A value of
'on' is equivalent to true, and
'off' is equivalent to false.
Thus, you can use the value of this property as a logical value. The value
is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Resize the text box to fit
    the text.

  • 'off' — Wrap the text to fit the
    width of the text box. Wrapping can cause some of the text to
    extend below the text box.

If you resize a text box when in plot edit mode, or if you
change the Position property, then the
FitBoxToText property changes to
'off'.

EdgeColorColor of box outline
[0 0 0]
(default) | RGB triplet | hexadecimal color code | 'r' | 'g' | 'b' | …

Color of box outline, specified as a three-element RGB triplet, a
hexadecimal color code, a color name, or a short name. The default value of
[0 0 0] corresponds to black.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0 0 1]

Example: '#0000FF'

BackgroundColorColor of text box background
'none'
(default) | RGB triplet | hexadecimal color code | 'r' | 'g' | 'b' | …

Color of text box background, specified as an RGB triplet, a hexadecimal
color code, a color name, or a short name.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0 0 1]

Example: '#0000FF'

FaceAlphaTransparency of background color
1 (default) | scalar value between 0 and 1 inclusive

Transparency of the background color, specified as a scalar value between
0 and 1. If the value is 1, then the color is opaque. To add transparency,
set the property to a value closer to 0, where 0 is completely
transparent.

LineStyleLine style of box outline
'-' (default) | '--' | ':' | '-.' | 'none'

Line style of box outline, specified as one of the options listed in this
table.

Line Style Description
'-' Solid line
'--' Dashed line
':' Dotted line
'-.' Dash-dotted line
'none' Box outline is invisible

LineWidthWidth of box outline
0.5 (default) | scalar numeric value

Width of box outline, specified as a scalar numeric value in
point units. One point equals 1/72 inch.

Example: 1.5

MarginSpace around text within the text box
5 (default) | scalar numeric value

The space around the text within the text box, specified as a scalar
numeric value in pixel units.

Position

expand all

PositionSize and location
[0.3 0.3 0.1 0.1] (default) | four-element vector

Size and location, specified as a four-element vector of the form
[x_begin y_begin length height]. The first two
elements specify the coordinates for the lower-left corner of the text box.
The second two elements specify the length and height of the text
box.

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.

Note

If the FitBoxToText property is set to
'on' and you change the String
property, then the Position property might not
reflect the latest changes until the next time the screen refreshes. To
ensure that the position value reflects the latest changes, call
drawnow before querying the position when working
in a script or function.

Example: [0.2 0.3 0.4 0.5]

RotationRotation angle in degrees
0 (default) | scalar numeric value

Rotation angle in degrees, specified as a scalar numeric value. Rotation angle is absolute
and not relative to previous rotations.

This table shows the resulting annotation rotation for the possible
Rotation values.

Rotation Value Resulting Rotation
0 Unrotated
Positive scalar value Rotated counterclockwise by the specified number of degrees
Negative scalar value Rotated clockwise by the specified number of degrees

The anchor point for rotation is the location specified by the first two elements of the
Position property vector, indicated by the [x y]
values.

Example: 45

Position units, specified as one of the values in this table.

Units Description
'normalized' (default) Normalized with respect to the figure, uipanel, or uitab that
contains the annotation. The lower-left corner of the container maps
to (0,0) and the upper-right corner maps to (1,1).
'inches' Inches.
'centimeters' Centimeters.
'characters'

Based on the default system font character size.

  • Character width = width of letter
    x.

  • Character height = distance between the baselines
    of two lines of text.

'points' Points. One point equals 1/72 inch.
'pixels'

Pixels.

Starting in R2015b, distances in
pixels are independent of your system resolution on Windows and Macintosh systems:

  • On Windows systems, a pixel is 1/96th of an inch.

  • On Macintosh systems, a pixel is 1/72nd of an
    inch.

On Linux systems, the size of a pixel is determined
by your system resolution.

All units are measured from the lower-left corner of the figure
window.

This property affects the Position property.
If you change the units, then it is good practice to return it to
the default value after completing your computation to prevent affecting
other functions that assume Units is set to the
default value.

If you specify the Position and Units properties
as Name,Value pairs when creating the object, then
the order of specification matters. If you want to define the position
with particular units, then you must set the Units property
before the Position property.

Horizontal alignment of the text within the text box, specified
as one of the values in this table.

Value Result
'left'

'center'

'right'

Vertical alignment of the text within the text box, specified
as one of the values in this table.

Value Result
'top'

'middle'

'bottom'

Note

The 'cap' and 'baseline' values
are not recommended. Use the 'top' and 'bottom' values,
respectively, instead.

Version History

Introduced before R2006a

expand all

R2022a: Rotate annotation

Rotate the annotation the specified number of degrees using the
Rotation property. The anchor point for rotation is the location
specified by the Position property, so the
Position property is unaffected by rotation.

TextBox Properties

Text box appearance and behavior

TextBox properties control the appearance
and behavior of a TextBox object. By changing property
values, you can modify certain aspects of the text box. Use dot notation to query and
set properties.

t = annotation('textbox');
sz = t.FontSize;
t.FontSize = 12;

expand all

Text to display, specified as a character vector, cell array of character vectors,
string array, categorical array, or numeric value. Specify a value according to how you
want the text to appear. This table lists the most common situations.

Appearance of Text Description of Value Example
One line of text Character vector or 1-by-1 string array.
str = 'My Text'

or

str = "My Text"
Multiple lines of text Cell array of character vectors or a string array.
str = {'First line','Second line'};

or

str = ["First line", "Second line"];
Text that includes a numeric variable Array that includes the number converted to a
char array. Use num2str to convert
the value.
x = 42;
str = ['The value is ',num2str(x)];
Text that includes special characters such as Greek letters or
mathematical symbols
Array that includes TeX markup. For a list of supported markup,
see the Interpreter property.
str = 'x ranges from 0 to 2pi'

Note

  • The words default, factory, and
    remove are reserved words that do not appear in text
    when quoted as normal characters. To display any of these words
    individually, precede them with a backslash, such as
    'default' or 'remove'.

  • If you specify this property as a categorical array, MATLAB® uses the values in the array, not the categories.

  • If you specify text that contains only a numeric value, the value is
    converted using sprintf('%g',value). For example,
    12345678 displays as
    1.23457e+07.

Text color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short
name. The default value of [0 0 0] corresponds to black.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0
0 1]

Example: '#0000FF'

Text interpreter, specified as one of these values:

  • 'tex' — Interpret characters using a subset of
    TeX markup.

  • 'latex' — Interpret characters using LaTeX
    markup.

  • 'none' — Display literal characters.

TeX Markup

By default, MATLAB supports a subset of TeX markup. Use TeX markup to add superscripts
and subscripts, modify the font type and color, and include special characters in
the text.

Modifiers remain in effect until the end of the text.
Superscripts and subscripts are an exception because they modify only the next character or the
characters within the curly braces. When you set the interpreter to 'tex',
the supported modifiers are as follows.

Modifier Description Example
^{ } Superscript 'text^{superscript}'
_{ } Subscript 'text_{subscript}'
bf Bold font 'bf text'
it Italic font 'it text'
sl Oblique font (usually the same as italic font) 'sl text'
rm Normal font 'rm text'
fontname{specifier} Font name — Replace
specifier with the name of
a font family. You can use this in combination with other modifiers.
'fontname{Courier} text'
fontsize{specifier} Font size —Replace
specifier with a numeric
scalar value in point units.
'fontsize{15} text'
color{specifier} Font color — Replace
specifier with one of
these colors: red, green,
yellow, magenta,
blue, black,
white, gray,
darkGreen, orange, or
lightBlue.
'color{magenta} text'
color[rgb]{specifier} Custom font color — Replace
specifier with a
three-element RGB triplet.
'color[rgb]{0,0.5,0.5} text'

This table lists the supported special characters for the
'tex' interpreter.

Character Sequence Symbol Character Sequence Symbol Character Sequence Symbol

alpha

α

upsilon

υ

sim

~

angle

phi

ϕ

leq

ast

*

chi

χ

infty

beta

β

psi

ψ

clubsuit

gamma

γ

omega

ω

diamondsuit

delta

δ

Gamma

Γ

heartsuit

epsilon

ϵ

Delta

Δ

spadesuit

zeta

ζ

Theta

Θ

leftrightarrow

eta

η

Lambda

Λ

leftarrow

theta

θ

Xi

Ξ

Leftarrow

vartheta

ϑ

Pi

Π

uparrow

iota

ι

Sigma

Σ

rightarrow

kappa

κ

Upsilon

ϒ

Rightarrow

lambda

λ

Phi

Φ

downarrow

mu

µ

Psi

Ψ

circ

º

nu

ν

Omega

Ω

pm

±

xi

ξ

forall

geq

pi

π

exists

propto

rho

ρ

ni

partial

sigma

σ

cong

bullet

varsigma

ς

approx

div

÷

tau

τ

Re

neq

equiv

oplus

aleph

Im

cup

wp

otimes

subseteq

oslash

cap

in

supseteq

supset

lceil

subset

int

cdot

·

o

ο

rfloor

neg

¬

nabla

lfloor

times

x

ldots

perp

surd

prime

´

wedge

varpi

ϖ

rceil

rangle

mid

|

vee

langle

copyright

©

LaTeX Markup

To use LaTeX markup, set the interpreter to 'latex'. For inline
mode, surround the markup with single dollar signs ($). For
display mode, surround the markup with double dollar signs
($$).

LaTeX Mode Example Result
Inline
'$int_1^{20} x^2 dx$'

Equation with LaTeX inline mode

Display
'$$int_1^{20} x^2 dx$$'

Equation with LaTeX display mode

The displayed text uses the default LaTeX font style. The
FontName, FontWeight, and
FontAngle properties do not have an effect. To change the
font style, use LaTeX markup.

The maximum size of the text that you can use with the LaTeX interpreter is 1200
characters. For multiline text, this reduces by about 10 characters per line.

For examples that use TeX and LaTeX, see Greek Letters and Special Characters in Chart Text. For more information about the LaTeX
system, see The LaTeX Project website at https://www.latex-project.org/.

Font

expand all

Font name, specified as a supported font name or 'FixedWidth'. To display
and print text properly, you must choose a font that your system supports. The default
font depends on your operating system and locale.

To use a fixed-width font that looks good in any locale, use 'FixedWidth'.
The fixed-width font relies on the root FixedWidthFontName
property. Setting the root FixedWidthFontName property causes an
immediate update of the display to use the new font.

Font size, specified as a scalar value greater than 0 in point units. The default font size
depends on the specific operating system and locale. One point equals 1/72 inch. To
change the font units, use the FontUnits property.

Example: 12

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical

Character thickness, specified as 'normal' or
'bold'.

MATLAB uses the FontWeight property to select a font from
those available on your system. Not all fonts have a bold weight. Therefore, specifying
a bold font weight can still result in the normal font weight.

Character slant, specified as 'normal' or
'italic'.

Not all fonts have both font styles. Therefore, the italic font might look the same
as the normal font.

FontUnitsFont size units
'points' (default) | 'inches' | 'centimeters' | 'normalized' | 'pixels'

Font size units, specified as one of the values in this
table.

Units Description
'points' Points. One point equals 1/72 inch.
'inches' Inches.
'centimeters' Centimeters.
'normalized' Interpret font size as a fraction of the parent
container height, typically a figure. If you resize the
container, the font size modifies accordingly. For
example, if the FontSize is
0.1 in normalized units, then the
text is 1/10 of the container height.
'pixels'

Pixels.

Starting in R2015b, distances in pixels are
independent of your system resolution on Windows® and Macintosh systems:

  • On Windows systems, a pixel is 1/96th of an
    inch.

  • On Macintosh systems, a pixel is 1/72nd of an
    inch.

On Linux® systems, the size of a pixel is
determined by your system resolution.

If you set both the font size and the font units in one function call, you
must set the FontUnits property first so that the axes
correctly interprets the specified font size.

Text Box

expand all

FitBoxToTextOption to fit box width and height to text
'on' (default) | on/off logical value

Option to fit the box width and height to the text, specified as
'on' or 'off', or as numeric or
logical 1 (true) or
0 (false). A value of
'on' is equivalent to true, and
'off' is equivalent to false.
Thus, you can use the value of this property as a logical value. The value
is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Resize the text box to fit
    the text.

  • 'off' — Wrap the text to fit the
    width of the text box. Wrapping can cause some of the text to
    extend below the text box.

If you resize a text box when in plot edit mode, or if you
change the Position property, then the
FitBoxToText property changes to
'off'.

EdgeColorColor of box outline
[0 0 0]
(default) | RGB triplet | hexadecimal color code | 'r' | 'g' | 'b' | …

Color of box outline, specified as a three-element RGB triplet, a
hexadecimal color code, a color name, or a short name. The default value of
[0 0 0] corresponds to black.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0 0 1]

Example: '#0000FF'

BackgroundColorColor of text box background
'none'
(default) | RGB triplet | hexadecimal color code | 'r' | 'g' | 'b' | …

Color of text box background, specified as an RGB triplet, a hexadecimal
color code, a color name, or a short name.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0 0 1]

Example: '#0000FF'

FaceAlphaTransparency of background color
1 (default) | scalar value between 0 and 1 inclusive

Transparency of the background color, specified as a scalar value between
0 and 1. If the value is 1, then the color is opaque. To add transparency,
set the property to a value closer to 0, where 0 is completely
transparent.

LineStyleLine style of box outline
'-' (default) | '--' | ':' | '-.' | 'none'

Line style of box outline, specified as one of the options listed in this
table.

Line Style Description
'-' Solid line
'--' Dashed line
':' Dotted line
'-.' Dash-dotted line
'none' Box outline is invisible

LineWidthWidth of box outline
0.5 (default) | scalar numeric value

Width of box outline, specified as a scalar numeric value in
point units. One point equals 1/72 inch.

Example: 1.5

MarginSpace around text within the text box
5 (default) | scalar numeric value

The space around the text within the text box, specified as a scalar
numeric value in pixel units.

Position

expand all

PositionSize and location
[0.3 0.3 0.1 0.1] (default) | four-element vector

Size and location, specified as a four-element vector of the form
[x_begin y_begin length height]. The first two
elements specify the coordinates for the lower-left corner of the text box.
The second two elements specify the length and height of the text
box.

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.

Note

If the FitBoxToText property is set to
'on' and you change the String
property, then the Position property might not
reflect the latest changes until the next time the screen refreshes. To
ensure that the position value reflects the latest changes, call
drawnow before querying the position when working
in a script or function.

Example: [0.2 0.3 0.4 0.5]

RotationRotation angle in degrees
0 (default) | scalar numeric value

Rotation angle in degrees, specified as a scalar numeric value. Rotation angle is absolute
and not relative to previous rotations.

This table shows the resulting annotation rotation for the possible
Rotation values.

Rotation Value Resulting Rotation
0 Unrotated
Positive scalar value Rotated counterclockwise by the specified number of degrees
Negative scalar value Rotated clockwise by the specified number of degrees

The anchor point for rotation is the location specified by the first two elements of the
Position property vector, indicated by the [x y]
values.

Example: 45

Position units, specified as one of the values in this table.

Units Description
'normalized' (default) Normalized with respect to the figure, uipanel, or uitab that
contains the annotation. The lower-left corner of the container maps
to (0,0) and the upper-right corner maps to (1,1).
'inches' Inches.
'centimeters' Centimeters.
'characters'

Based on the default system font character size.

  • Character width = width of letter
    x.

  • Character height = distance between the baselines
    of two lines of text.

'points' Points. One point equals 1/72 inch.
'pixels'

Pixels.

Starting in R2015b, distances in
pixels are independent of your system resolution on Windows and Macintosh systems:

  • On Windows systems, a pixel is 1/96th of an inch.

  • On Macintosh systems, a pixel is 1/72nd of an
    inch.

On Linux systems, the size of a pixel is determined
by your system resolution.

All units are measured from the lower-left corner of the figure
window.

This property affects the Position property.
If you change the units, then it is good practice to return it to
the default value after completing your computation to prevent affecting
other functions that assume Units is set to the
default value.

If you specify the Position and Units properties
as Name,Value pairs when creating the object, then
the order of specification matters. If you want to define the position
with particular units, then you must set the Units property
before the Position property.

Horizontal alignment of the text within the text box, specified
as one of the values in this table.

Value Result
'left'

'center'

'right'

Vertical alignment of the text within the text box, specified
as one of the values in this table.

Value Result
'top'

'middle'

'bottom'

Note

The 'cap' and 'baseline' values
are not recommended. Use the 'top' and 'bottom' values,
respectively, instead.

Version History

Introduced before R2006a

expand all

R2022a: Rotate annotation

Rotate the annotation the specified number of degrees using the
Rotation property. The anchor point for rotation is the location
specified by the Position property, so the
Position property is unaffected by rotation.

I want to change Font Size for xlabel, ylabel, axis size, legend font size a.k.a everything at once, is this possible? By default, font is Helvetica 10.

Is there way to change this?

I want to use ‘FontSize’,14, for x or y labels.

Matteo Ragni's user avatar

Matteo Ragni

2,7771 gold badge22 silver badges33 bronze badges

asked Jan 19, 2012 at 22:43

sosruko's user avatar

Jonas’s answer is good, but I had to modify it slightly to get every piece of text on the screen to change:

set(gca,'FontSize',30,'fontWeight','bold')

set(findall(gcf,'type','text'),'FontSize',30,'fontWeight','bold')

answered Jul 11, 2012 at 18:55

sergeyf's user avatar

sergeyfsergeyf

1,00411 silver badges10 bronze badges

1

If you want to change font size for all the text in a figure, you can use findall to find all text handles, after which it’s easy:

figureHandle = gcf;
%# make all text in the figure to size 14 and bold
set(findall(figureHandle,'type','text'),'fontSize',14,'fontWeight','bold')

answered Jan 19, 2012 at 22:58

Jonas's user avatar

JonasJonas

74.5k10 gold badges137 silver badges177 bronze badges

1

It’s possible to change default fonts, both for the axes and for other text, by adding the following lines to the startup.m file.

% Change default axes fonts.
set(0,'DefaultAxesFontName', 'Times New Roman')
set(0,'DefaultAxesFontSize', 14)

% Change default text fonts.
set(0,'DefaultTextFontname', 'Times New Roman')
set(0,'DefaultTextFontSize', 14)

If you don’t know if you have a startup.m file, run

which startup

to find its location. If Matlab says there isn’t one, run

userpath

to know where it should be placed.

answered Jan 21, 2012 at 23:18

Alexandre Chabot's user avatar

If anyone was wondering how to change the font sizes without messing around with the Matlab default fonts, and change every font in a figure, I found this thread where suggests this:

set(findall(fig, '-property', 'FontSize'), 'FontSize', 10, 'fontWeight', 'bold')

findall is a pretty handy command and in the case above it really finds all the children who have a 'FontSize' property: axes lables, axes titles, pushbuttons, etc.

Hope it helps.

answered Nov 12, 2013 at 0:04

p8me's user avatar

p8mep8me

1,8401 gold badge15 silver badges23 bronze badges

To change the title font size, use the following example

title('mytitle','FontSize',12);

to the change the graph axes label font size, do the following

axes('FontSize',24);

answered Jan 19, 2012 at 22:53

suresh's user avatar

sureshsuresh

1,1091 gold badge8 silver badges24 bronze badges

Jonas’s answer does not change the font size of the axes.
Sergeyf’s answer does not work when there are multiple subplots.

Here is a modification of their answers that works for me when I have multiple subplots:

set(findall(gcf,'type','axes'),'fontsize',30)
set(findall(gcf,'type','text'),'fontSize',30) 

answered Sep 4, 2013 at 11:43

omian's user avatar

omianomian

511 silver badge3 bronze badges

To change the default property for your entire MATLAB session, see the documentation on how default properties are handled.

As an example:

set(0,'DefaultAxesFontSize',22)
x=1:200; y=sin(x);
plot(x,y)
title('hello'); xlabel('x'); ylabel('sin(x)')

answered Jan 19, 2012 at 23:02

mbauman's user avatar

mbaumanmbauman

30.6k4 gold badges89 silver badges123 bronze badges

0

7 ответов

Ответ Jonas — это хорошо, но мне пришлось немного изменить его, чтобы изменить каждый текст на экране:

set(gca,'FontSize',30,'fontWeight','bold')

set(findall(gcf,'type','text'),'FontSize',30,'fontWeight','bold')

sergeyf
11 июль 2012, в 19:47

Поделиться

Если вы хотите изменить размер шрифта для всего текста на рисунке, вы можете использовать findall, чтобы найти все текстовые дескрипторы, после чего легко:

figureHandle = gcf;
%# make all text in the figure to size 14 and bold
set(findall(figureHandle,'type','text'),'fontSize',14,'fontWeight','bold')

Jonas
20 янв. 2012, в 00:25

Поделиться

Можно изменить шрифты по умолчанию, как для осей, так и для другого текста, добавив следующие строки в файл startup.m.

% Change default axes fonts.
set(0,'DefaultAxesFontName', 'Times New Roman')
set(0,'DefaultAxesFontSize', 14)

% Change default text fonts.
set(0,'DefaultTextFontname', 'Times New Roman')
set(0,'DefaultTextFontSize', 14)

Если вы не знаете, есть ли файл startup.m, запустите

which startup

чтобы найти его местоположение. Если Matlab говорит, что его нет, запустите

userpath

чтобы узнать, где он должен быть размещен.

Alexandre Chabot
22 янв. 2012, в 01:13

Поделиться

Если кто-то задавался вопросом, как изменить размер шрифта, не вмешиваясь в шрифты по умолчанию Matlab и изменить каждый шрифт на фигуре, я нашел эта нить, где предлагает это:

set(findall(fig, '-property', 'FontSize'), 'FontSize', 10, 'fontWeight', 'bold')

findall — довольно удобная команда, и в приведенном выше случае он действительно находит всех детей, у которых есть свойство 'FontSize': осями, названиями осей, кнопками и т.д.

Надеюсь, что это поможет.

pm89
12 нояб. 2013, в 00:22

Поделиться

Ответ Jonas не изменяет размер шрифта осей.
Ответ Sergeyf не работает, когда есть несколько подзаговоров.

Вот модификация их ответов, которая работает для меня, когда у меня есть несколько подзаговоров:

set(findall(gcf,'type','axes'),'fontsize',30)
set(findall(gcf,'type','text'),'fontSize',30) 

omian
04 сен. 2013, в 12:48

Поделиться

Чтобы изменить размер шрифта заголовка, используйте следующий пример

title('mytitle','FontSize',12);

чтобы изменить размер шрифта метки осей графа, выполните следующие действия

axes('FontSize',24);

suresh
19 янв. 2012, в 23:47

Поделиться

Чтобы изменить свойство по умолчанию для всего сеанса MATLAB, см. документацию по как обрабатываются свойства по умолчанию.

В качестве примера:

set(0,'DefaultAxesFontSize',22)
x=1:200; y=sin(x);
plot(x,y)
title('hello'); xlabel('x'); ylabel('sin(x)')

Matt B.
19 янв. 2012, в 23:48

Поделиться

Ещё вопросы

  • 1установить расширенную ширину и высоту ImageView программно — Android
  • 0Добавить новую строку в Datatable из табличных значений?
  • 1Как хранить ключ шифрования .NET
  • 1Как запустить файл MATLAB (файл .m) из Java?
  • 0Замените ресурсы на путь CDN, используя grunt
  • 0Подключение от парусов в ec2 к mysql в rds дает ошибку тайм-аута неактивного рукопожатия
  • 1Шаблон дизайна медиатора: Почему классы должны информировать медиатора о своем поведении?
  • 0Как отключить jQuery Datepicker из MySQL значение / содержание
  • 0неопределенная ссылка при перегрузке cout
  • 1Вызов кодов за другим был закончен node.js
  • 0$ location.path () возвращает неправильное значение
  • 0Обновить первое вхождение значения во временном интервале
  • 1Можно ли получить расширение или тип файла из файла, загруженного в MemoryStream?
  • 0OpenThread с несуществующим идентификатором потока
  • 1Справка по матрице: как postScale влияет на часть перевода матрицы?
  • 0«Папка папки» в htaccess
  • 0ошибка в меню суперфиши в режиме просмотра совместимости IE
  • 0Угловая директива множественных входов одной модели
  • 0postgresql группа по
  • 1Буферизация / синхронизация нескольких аудиопотоков в JavaScript
  • 0изменить отображаемое имя ячейки в выводе sql запроса
  • 0jQuery — после добавления значения в поле ввода, не учитывается функцией фильтра
  • 1Как извлечь конкретное число в строку, окруженную цифрами и текстом C #
  • 1Модуль HTTP Node.js: Ответ + Запрос
  • 0Как получить доступ к ассоциативному массиву в yii2
  • 1как вызывать Common Lisp коды из метода JSCL
  • 0Intellisense: аргумент типа «HWND» несовместим с параметром типа «rawData :: HWND»
  • 1передать параметры из C ++ для сборки в Android
  • 0Ионный шаблон не работает на мобильном телефоне
  • 0Полный календарь jQuery не отображает просмотр месяца по умолчанию
  • 0Зачем использовать классы или идентификаторы в элементе HTML?
  • 0Измените UL стиля выбора JQuery для работы без BootstrapJS
  • 1Программирование последовательного порта на Android-Beagleboard
  • 0BST код не работает с большим количеством
  • 0sql: выбор значения в таблице атрибутов
  • 0AngularJ вызывают функцию только после вызова заводской функции
  • 1Масштаб построения диаграммы области, когда все значения положительные
  • 1поиск слова документа в c #
  • 1Рабочий стол Windows 7 без датчика местоположения
  • 0Фильтрация гиперссылки в неупорядоченном списке
  • 0JSF как разделить формы
  • 0Бэкэнд без состояния безопасен?
  • 1Необходим ли bindService для локального (того же процесса) сервиса?
  • 0Статус 400 Запрос, отправленный клиентом, был синтаксически неверным. Angularjs http
  • 1Android Tabhost пользовательский цвет
  • 1Ограничить разрешение для передаваемого изображения
  • 0Как разместить текст после эскизов внизу?
  • 0Qt, перечисления и компилятор метаобъектов
  • 0Как сделать разделение в запросе SQL между двумя столбцами
  • 1Как я могу отладить файл текстового шаблона mvc scaffolding?

Text Properties

Subplot text appearance and behavior

Text properties control the appearance and
behavior of the Text object used to title a grid of subplots. By changing
property values, you can modify certain aspects of the text. For example:

t = sgtitle('Title Text')
t.FontSize = 14;

expand all

StringText to display
'' (default) | character vector | cell array of character vectors | string array | categorical array | numeric value

Text to display, specified as a character vector, cell array of character vectors,
string array, categorical array, or numeric value.

Example: 'my label'

Example: {'first line','second line'}

Example: string('my label')

Example: 123

To include numeric variables with text, use the num2str function. For
example:

x = 42;
txt = ['The value is ',num2str(x)];

To include special characters, such as superscripts, subscripts, Greek letters, or
mathematical symbols use TeX markup. For a list of supported markup, see the
Interpreter property.

To create multiline text:

  • Use a cell array, where each cell contains a line of text, such as
    {'first line','second line'}.

  • Use a string array, where each element contains a line of text, such as
    string({'line one','line two'}).

  • Use a character array, where each row contains the same number of characters,
    such as ['abc'; 'ab '].

  • Use sprintf to create text with a new
    line character, such as sprintf('first line n second line').
    This property converts text with new line characters to cell arrays.

Text that contains only a numeric value is converted using
sprintf('%g',value). For example, 12345678
displays as 1.23457e+07.

If you specify this property as a categorical array, MATLAB® uses the values in the array, not the categories.

Text color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short
name. The default value of [0 0 0] corresponds to black.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0
0 1]

Example: '#0000FF'

Text interpreter, specified as one of these values:

  • 'tex' — Interpret characters using a subset of
    TeX markup.

  • 'latex' — Interpret characters using LaTeX
    markup.

  • 'none' — Display literal characters.

TeX Markup

By default, MATLAB supports a subset of TeX markup. Use TeX markup to add superscripts
and subscripts, modify the font type and color, and include special characters in
the text.

Modifiers remain in effect until the end of the text.
Superscripts and subscripts are an exception because they modify only the next character or the
characters within the curly braces. When you set the interpreter to 'tex',
the supported modifiers are as follows.

Modifier Description Example
^{ } Superscript 'text^{superscript}'
_{ } Subscript 'text_{subscript}'
bf Bold font 'bf text'
it Italic font 'it text'
sl Oblique font (usually the same as italic font) 'sl text'
rm Normal font 'rm text'
fontname{specifier} Font name — Replace
specifier with the name of
a font family. You can use this in combination with other modifiers.
'fontname{Courier} text'
fontsize{specifier} Font size —Replace
specifier with a numeric
scalar value in point units.
'fontsize{15} text'
color{specifier} Font color — Replace
specifier with one of
these colors: red, green,
yellow, magenta,
blue, black,
white, gray,
darkGreen, orange, or
lightBlue.
'color{magenta} text'
color[rgb]{specifier} Custom font color — Replace
specifier with a
three-element RGB triplet.
'color[rgb]{0,0.5,0.5} text'

This table lists the supported special characters for the
'tex' interpreter.

Character Sequence Symbol Character Sequence Symbol Character Sequence Symbol

alpha

α

upsilon

υ

sim

~

angle

phi

ϕ

leq

ast

*

chi

χ

infty

beta

β

psi

ψ

clubsuit

gamma

γ

omega

ω

diamondsuit

delta

δ

Gamma

Γ

heartsuit

epsilon

ϵ

Delta

Δ

spadesuit

zeta

ζ

Theta

Θ

leftrightarrow

eta

η

Lambda

Λ

leftarrow

theta

θ

Xi

Ξ

Leftarrow

vartheta

ϑ

Pi

Π

uparrow

iota

ι

Sigma

Σ

rightarrow

kappa

κ

Upsilon

ϒ

Rightarrow

lambda

λ

Phi

Φ

downarrow

mu

µ

Psi

Ψ

circ

º

nu

ν

Omega

Ω

pm

±

xi

ξ

forall

geq

pi

π

exists

propto

rho

ρ

ni

partial

sigma

σ

cong

bullet

varsigma

ς

approx

div

÷

tau

τ

Re

neq

equiv

oplus

aleph

Im

cup

wp

otimes

subseteq

oslash

cap

in

supseteq

supset

lceil

subset

int

cdot

·

o

ο

rfloor

neg

¬

nabla

lfloor

times

x

ldots

perp

surd

prime

´

wedge

varpi

ϖ

rceil

rangle

mid

|

vee

langle

copyright

©

LaTeX Markup

To use LaTeX markup, set the interpreter to 'latex'. For inline
mode, surround the markup with single dollar signs ($). For
display mode, surround the markup with double dollar signs
($$).

LaTeX Mode Example Result
Inline
'$int_1^{20} x^2 dx$'

Equation with LaTeX inline mode

Display
'$$int_1^{20} x^2 dx$$'

Equation with LaTeX display mode

The displayed text uses the default LaTeX font style. The
FontName, FontWeight, and
FontAngle properties do not have an effect. To change the
font style, use LaTeX markup.

The maximum size of the text that you can use with the LaTeX interpreter is 1200
characters. For multiline text, this reduces by about 10 characters per line.

For examples that use TeX and LaTeX, see Greek Letters and Special Characters in Chart Text. For more information about the LaTeX
system, see The LaTeX Project website at https://www.latex-project.org/.

HorizontalAlignmentHorizontal alignment
'center' (default) | 'left' | 'right'

Horizontal alignment of text within the text box, specified as
'center', 'left', or
'right'.

Font

expand all

Font name, specified as a supported font name or 'FixedWidth'. To display
and print text properly, you must choose a font that your system supports. The default
font depends on your operating system and locale.

To use a fixed-width font that looks good in any locale, use 'FixedWidth'.
The fixed-width font relies on the root FixedWidthFontName
property. Setting the root FixedWidthFontName property causes an
immediate update of the display to use the new font.

Font size, specified as a scalar value greater than zero in point units. The default font
size depends on the specific operating system and locale. One point equals
1/72 inch. To change the font units, use the
FontUnits property.

Example: 12

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

FontSizeModeSelection mode for font size
'auto' (default) | 'manual'

Selection mode for the font size, specified as either 'auto' or
'manual'.

Character thickness, specified as 'normal' or
'bold'.

MATLAB uses the FontWeight property to select a font from
those available on your system. Not all fonts have a bold weight. Therefore, specifying
a bold font weight can still result in the normal font weight.

Character slant, specified as 'normal' or
'italic'.

Not all fonts have both font styles. Therefore, the italic font might look the same
as the normal font.

FontUnitsFont size units
'points' (default) | 'inches' | 'centimeters' | 'normalized' | 'pixels'

Font size units, specified as one of the values in this table.

Units Description
'points' Points. One point equals 1/72 inch.
'inches' Inches.
'centimeters' Centimeters.
'normalized' Interpret font size as a fraction of the axes plot box height. If you
resize the axes, the font size modifies accordingly. For example, if the
FontSize is 0.1 in normalized units,
then the text is 1/10 of the plot box height.
'pixels'

Pixels.

Starting in R2015b, distances in pixels are
independent of your system resolution on Windows® and Macintosh systems:

  • On Windows systems, a pixel is 1/96th of an inch.

  • On Macintosh systems, a pixel is 1/72nd of an inch.

On Linux® systems, the size of a pixel is determined by your system
resolution.

If you set both the font size and the font units in one function call, you must set
the FontUnits property first so that the axes correctly interprets
the specified font size.

Text Box

expand all

EdgeColorColor of box outline
'none' (default) | RGB triplet | hexadecimal color code | 'r' | 'g' | 'b' | …

Color of box outline, specified as an RGB triplet, a hexadecimal color code, a color
name, or a short name.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0 0 1]

Example: '#0000FF'

BackgroundColorColor of text box background
'none' (default) | RGB triplet | hexadecimal color code | 'r' | 'g' | 'b' | …

Color of text box background, specified as an RGB triplet, a hexadecimal color code,
a color name, or a short name.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0 0 1]

Example: '#0000FF'

LineStyleLine style of box outline
'-' (default) | '--' | ':' | '-.' | 'none'

Line style of box outline, specified as one of the options in this
table.

Line Style Description Resulting Line
'-' Solid line

'--' Dashed line

':' Dotted line

'-.' Dash-dotted line

'none' Line is invisible  

LineWidthWidth of box outline
0.5 (default) | scalar numeric value

Width of box outline, specified as a scalar numeric value in
point units. One point equals 1/72 inch.

Example: 1.5

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

MarginSpace around text within the text box
3 (default) | scalar numeric value

The space around the text within the text box, specified as scalar numeric value in
point units.

MATLAB uses the Extent property value plus the
Margin property value to determine the size of the text box.

Example: 8

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Interactivity

expand all

State of visibility, specified as 'on' or 'off', or as
numeric or logical 1 (true) or
0 (false). A value of 'on'
is equivalent to true, and 'off' is equivalent to
false. Thus, you can use the value of this property as a logical
value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Display the object.

  • 'off' — Hide the object without deleting it. You
    still can access the properties of an invisible object.

Context menu, specified as a ContextMenu object. Use this property
to display a context menu when you right-click the object. Create the context menu using
the uicontextmenu function.

Note

If the PickableParts property is set to
'none' or if the HitTest property is set
to 'off', then the context menu does not appear.

Selection state, specified as 'on' or 'off', or as
numeric or logical 1 (true) or
0 (false). A value of 'on'
is equivalent to true, and 'off' is equivalent to
false. Thus, you can use the value of this property as a logical
value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Selected. If you click the object when in
    plot edit mode, then MATLAB sets its Selected property to
    'on'. If the SelectionHighlight
    property also is set to 'on', then MATLAB displays selection handles around the object.

  • 'off' — Not selected.

Display of selection handles when selected, specified as 'on' or
'off', or as numeric or logical 1
(true) or 0 (false). A
value of 'on' is equivalent to true, and 'off' is
equivalent to false. Thus, you can use the value of this property as
a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Display selection handles when the
    Selected property is set to
    'on'.

  • 'off' — Never display selection handles, even
    when the Selected property is set to
    'on'.

Callbacks

expand all

Mouse-click callback, specified as one of these values:

  • Function handle

  • Cell array containing a function handle and additional
    arguments

  • Character vector that is a valid MATLAB command
    or function, which is evaluated in the base workspace (not recommended)

Use this property to execute code when you click the object.
If you specify this property using a function handle, then MATLAB passes
two arguments to the callback function when executing the callback:

  • Clicked object — Access properties of the clicked object from within
    the callback function.

  • Event data — Empty argument. Replace it with the tilde character
    (~) in the function definition to indicate that this
    argument is not used.

For more information on how to use function handles
to define callback functions, see Create Callbacks for Graphics Objects.

Note

If the PickableParts property is set to 'none' or
if the HitTest property is set to 'off',
then this callback does not execute.

Object creation function, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

For more information about specifying a callback as a function handle, cell array, or character vector, see Create Callbacks for Graphics Objects.

This property specifies a callback function to execute when MATLAB creates the object. MATLAB initializes all property values before executing the CreateFcn callback. If you do not specify the CreateFcn property, then MATLAB executes a default creation function.

Setting the CreateFcn property on an existing component has no effect.

If you specify this property as a function handle or cell array, you can access the object that is being created using the first argument of the callback function. Otherwise, use the gcbo function to access the object.

Object deletion function, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

For more information about specifying a callback as a function handle, cell array, or character vector, see Create Callbacks for Graphics Objects.

This property specifies a callback function to execute when MATLAB deletes the object. MATLAB executes the DeleteFcn callback before destroying the
properties of the object. If you do not specify the DeleteFcn
property, then MATLAB executes a default deletion function.

If you specify this property as a function handle or cell array, you can access the object that is being deleted using the first argument of the callback function. Otherwise, use the gcbo function to access the object.

Callback Execution Control

expand all

Callback interruption, specified as 'on' or 'off', or as
numeric or logical 1 (true) or
0 (false). A value of 'on'
is equivalent to true, and 'off' is equivalent to
false. Thus, you can use the value of this property as a logical
value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

This property determines if a running callback can be interrupted. There are two callback
states to consider:

  • The running callback is the currently executing
    callback.

  • The interrupting callback is a callback that tries
    to interrupt the running callback.

MATLAB determines callback interruption behavior whenever it executes a command that
processes the callback queue. These commands include drawnow, figure, uifigure, getframe, waitfor, and pause.

If the running callback does not contain one of these commands, then no interruption
occurs. MATLAB first finishes executing the running callback, and later executes the
interrupting callback.

If the running callback does contain one of these commands, then the
Interruptible property of the object that owns the running
callback determines if the interruption occurs:

  • If the value of Interruptible is
    'off', then no interruption occurs. Instead, the
    BusyAction property of the object that owns the
    interrupting callback determines if the interrupting callback is discarded or
    added to the callback queue.

  • If the value of Interruptible is 'on',
    then the interruption occurs. The next time MATLAB processes the callback queue, it stops the execution of the
    running callback and executes the interrupting callback. After the interrupting
    callback completes, MATLAB then resumes executing the running callback.

Note

Callback interruption and execution behave differently in these situations:

  • If the interrupting callback is a DeleteFcn,
    CloseRequestFcn, or
    SizeChangedFcn callback, then the interruption
    occurs regardless of the Interruptible property
    value.

  • If the running callback is currently executing the
    waitfor function, then the interruption occurs
    regardless of the Interruptible property
    value.

  • If the interrupting callback is owned by a Timer object, then the callback executes according to
    schedule regardless of the Interruptible property
    value.

Note

When an interruption occurs, MATLAB does not save the state of properties or the display. For example, the
object returned by the gca or gcf command might change when
another callback executes.

Callback queuing, specified as 'queue' or 'cancel'. The BusyAction property determines how MATLAB handles the execution of interrupting callbacks. There are two callback states to consider:

  • The running callback is the currently executing callback.

  • The interrupting callback is a callback that tries to interrupt the running callback.

The BusyAction property determines callback queuing behavior only
when both of these conditions are met:

  • The running callback contains a command that processes the callback queue,
    such as drawnow, figure, uifigure, getframe, waitfor, or pause.

  • The value of the Interruptible property of the object
    that owns the running callback is 'off'.

Under these conditions, the BusyAction property of the
object that owns the interrupting callback determines how MATLAB handles the interrupting callback. These are possible values of the
BusyAction property:

  • 'queue' — Puts the interrupting callback in a queue to be processed after the running callback finishes execution.

  • 'cancel' — Does not execute the interrupting callback.

Ability to capture mouse clicks, specified as one of these values:

  • 'visible' — Capture mouse clicks only when
    visible. The Visible property must be set to
    'on'. The HitTest property
    determines if the Text object responds to the click or if an ancestor does.

  • 'all' — Capture mouse clicks regardless of
    visibility. The Visible property can be set to
    'on' or 'off'. The
    HitTest property determines if the Text object responds to
    the click or if an ancestor does.

  • 'none' — Cannot capture
    mouse clicks. Clicking the Text object
    passes the click to the object below it in the current view of the
    figure window, which is typically the axes or the figure. The HitTest property
    has no effect.

If you want an object to be clickable when it is underneath
other objects that you do not want to be clickable, then set the PickableParts property
of the other objects to 'none' so that the click
passes through them.

Response to captured mouse clicks, specified as 'on' or
'off', or as numeric or logical 1
(true) or 0 (false). A
value of 'on' is equivalent to true, and 'off' is
equivalent to false. Thus, you can use the value of this property as
a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Trigger the
    ButtonDownFcn callback of the Text object. If you have
    defined the ContextMenu property, then invoke the
    context menu.

  • 'off' — Trigger the callbacks for the nearest
    ancestor of the Text object that has one of these:

    • HitTest property set to
      'on'

    • PickableParts property set to a value that
      enables the ancestor to capture mouse clicks

Note

The PickableParts property determines if
the Text object can capture
mouse clicks. If it cannot, then the HitTest property
has no effect.

This property is read-only.

Deletion status, returned as an on/off logical value of type matlab.lang.OnOffSwitchState.

MATLAB sets the BeingDeleted property to
'on' when the DeleteFcn callback begins
execution. The BeingDeleted property remains set to
'on' until the component object no longer exists.

Check the value of the BeingDeleted property to verify that the object is not about to be deleted before querying or modifying it.

Parent/Child

expand all

ParentParent
Figure object

Parent, specified as a Figure object.

The object has no children. You cannot set this property.

Visibility of the object handle in the Children property
of the parent, specified as one of these values:

  • 'on' — Object handle is
    always visible.

  • 'off' — Object handle is invisible at
    all times. This option is useful for preventing unintended
    changes by another function. Set the
    HandleVisibility to
    'off' to temporarily hide the handle
    during the execution of that function.

  • 'callback' — Object handle is visible
    from within callbacks or functions invoked by callbacks, but not
    from within functions invoked from the command line. This option
    blocks access to the object at the command line, but permits
    callback functions to access it.

If the object is not listed in the Children property of the parent, then
functions that obtain object handles by searching the object hierarchy or querying
handle properties cannot return it. Examples of such functions include the
get, findobj, gca, gcf, gco, newplot, cla, clf, and close functions.

Hidden object handles are still valid. Set the root ShowHiddenHandles property
to 'on' to list all object handles regardless of
their HandleVisibility property setting.

Identifiers

expand all

TypeType of graphics object
'subplottext'

This property is read-only.

Type of graphics object, returned as 'subplottext'. Use this
property to find all objects of a given type within a plotting hierarchy, for example,
searching for the type using findobj.

Object identifier, specified as a character vector or string scalar. You can specify a unique Tag value to serve as an identifier for an object. When you need access to the object elsewhere in your code, you can use the findobj function to search for the object based on the Tag value.

User data, specified as any MATLAB array. For example, you can specify a scalar, vector, matrix, cell array, character array, table, or structure. Use this property to store arbitrary data on an object.

If you are working in App Designer, create public or private properties in the app to share data instead of using the UserData property. For more information, see Share Data Within App Designer Apps.

Version History

Introduced in R2018b

expand all

R2020a: UIContextMenu property is not recommended

Setting or getting UIContextMenu property is not recommended. Instead,
use the ContextMenu
property, which accepts the same type of input and behaves the same way as the
UIContextMenu property.

There are no plans to remove the UIContextMenu property, but it is no
longer listed when you call the set, get, or
properties functions on the Text object.

Text Properties

Subplot text appearance and behavior

Text properties control the appearance and
behavior of the Text object used to title a grid of subplots. By changing
property values, you can modify certain aspects of the text. For example:

t = sgtitle('Title Text')
t.FontSize = 14;

expand all

StringText to display
'' (default) | character vector | cell array of character vectors | string array | categorical array | numeric value

Text to display, specified as a character vector, cell array of character vectors,
string array, categorical array, or numeric value.

Example: 'my label'

Example: {'first line','second line'}

Example: string('my label')

Example: 123

To include numeric variables with text, use the num2str function. For
example:

x = 42;
txt = ['The value is ',num2str(x)];

To include special characters, such as superscripts, subscripts, Greek letters, or
mathematical symbols use TeX markup. For a list of supported markup, see the
Interpreter property.

To create multiline text:

  • Use a cell array, where each cell contains a line of text, such as
    {'first line','second line'}.

  • Use a string array, where each element contains a line of text, such as
    string({'line one','line two'}).

  • Use a character array, where each row contains the same number of characters,
    such as ['abc'; 'ab '].

  • Use sprintf to create text with a new
    line character, such as sprintf('first line n second line').
    This property converts text with new line characters to cell arrays.

Text that contains only a numeric value is converted using
sprintf('%g',value). For example, 12345678
displays as 1.23457e+07.

If you specify this property as a categorical array, MATLAB® uses the values in the array, not the categories.

Text color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short
name. The default value of [0 0 0] corresponds to black.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0
0 1]

Example: '#0000FF'

Text interpreter, specified as one of these values:

  • 'tex' — Interpret characters using a subset of
    TeX markup.

  • 'latex' — Interpret characters using LaTeX
    markup.

  • 'none' — Display literal characters.

TeX Markup

By default, MATLAB supports a subset of TeX markup. Use TeX markup to add superscripts
and subscripts, modify the font type and color, and include special characters in
the text.

Modifiers remain in effect until the end of the text.
Superscripts and subscripts are an exception because they modify only the next character or the
characters within the curly braces. When you set the interpreter to 'tex',
the supported modifiers are as follows.

Modifier Description Example
^{ } Superscript 'text^{superscript}'
_{ } Subscript 'text_{subscript}'
bf Bold font 'bf text'
it Italic font 'it text'
sl Oblique font (usually the same as italic font) 'sl text'
rm Normal font 'rm text'
fontname{specifier} Font name — Replace
specifier with the name of
a font family. You can use this in combination with other modifiers.
'fontname{Courier} text'
fontsize{specifier} Font size —Replace
specifier with a numeric
scalar value in point units.
'fontsize{15} text'
color{specifier} Font color — Replace
specifier with one of
these colors: red, green,
yellow, magenta,
blue, black,
white, gray,
darkGreen, orange, or
lightBlue.
'color{magenta} text'
color[rgb]{specifier} Custom font color — Replace
specifier with a
three-element RGB triplet.
'color[rgb]{0,0.5,0.5} text'

This table lists the supported special characters for the
'tex' interpreter.

Character Sequence Symbol Character Sequence Symbol Character Sequence Symbol

alpha

α

upsilon

υ

sim

~

angle

phi

ϕ

leq

ast

*

chi

χ

infty

beta

β

psi

ψ

clubsuit

gamma

γ

omega

ω

diamondsuit

delta

δ

Gamma

Γ

heartsuit

epsilon

ϵ

Delta

Δ

spadesuit

zeta

ζ

Theta

Θ

leftrightarrow

eta

η

Lambda

Λ

leftarrow

theta

θ

Xi

Ξ

Leftarrow

vartheta

ϑ

Pi

Π

uparrow

iota

ι

Sigma

Σ

rightarrow

kappa

κ

Upsilon

ϒ

Rightarrow

lambda

λ

Phi

Φ

downarrow

mu

µ

Psi

Ψ

circ

º

nu

ν

Omega

Ω

pm

±

xi

ξ

forall

geq

pi

π

exists

propto

rho

ρ

ni

partial

sigma

σ

cong

bullet

varsigma

ς

approx

div

÷

tau

τ

Re

neq

equiv

oplus

aleph

Im

cup

wp

otimes

subseteq

oslash

cap

in

supseteq

supset

lceil

subset

int

cdot

·

o

ο

rfloor

neg

¬

nabla

lfloor

times

x

ldots

perp

surd

prime

´

wedge

varpi

ϖ

rceil

rangle

mid

|

vee

langle

copyright

©

LaTeX Markup

To use LaTeX markup, set the interpreter to 'latex'. For inline
mode, surround the markup with single dollar signs ($). For
display mode, surround the markup with double dollar signs
($$).

LaTeX Mode Example Result
Inline
'$int_1^{20} x^2 dx$'

Equation with LaTeX inline mode

Display
'$$int_1^{20} x^2 dx$$'

Equation with LaTeX display mode

The displayed text uses the default LaTeX font style. The
FontName, FontWeight, and
FontAngle properties do not have an effect. To change the
font style, use LaTeX markup.

The maximum size of the text that you can use with the LaTeX interpreter is 1200
characters. For multiline text, this reduces by about 10 characters per line.

For examples that use TeX and LaTeX, see Greek Letters and Special Characters in Chart Text. For more information about the LaTeX
system, see The LaTeX Project website at https://www.latex-project.org/.

HorizontalAlignmentHorizontal alignment
'center' (default) | 'left' | 'right'

Horizontal alignment of text within the text box, specified as
'center', 'left', or
'right'.

Font

expand all

Font name, specified as a supported font name or 'FixedWidth'. To display
and print text properly, you must choose a font that your system supports. The default
font depends on your operating system and locale.

To use a fixed-width font that looks good in any locale, use 'FixedWidth'.
The fixed-width font relies on the root FixedWidthFontName
property. Setting the root FixedWidthFontName property causes an
immediate update of the display to use the new font.

Font size, specified as a scalar value greater than zero in point units. The default font
size depends on the specific operating system and locale. One point equals
1/72 inch. To change the font units, use the
FontUnits property.

Example: 12

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

FontSizeModeSelection mode for font size
'auto' (default) | 'manual'

Selection mode for the font size, specified as either 'auto' or
'manual'.

Character thickness, specified as 'normal' or
'bold'.

MATLAB uses the FontWeight property to select a font from
those available on your system. Not all fonts have a bold weight. Therefore, specifying
a bold font weight can still result in the normal font weight.

Character slant, specified as 'normal' or
'italic'.

Not all fonts have both font styles. Therefore, the italic font might look the same
as the normal font.

FontUnitsFont size units
'points' (default) | 'inches' | 'centimeters' | 'normalized' | 'pixels'

Font size units, specified as one of the values in this table.

Units Description
'points' Points. One point equals 1/72 inch.
'inches' Inches.
'centimeters' Centimeters.
'normalized' Interpret font size as a fraction of the axes plot box height. If you
resize the axes, the font size modifies accordingly. For example, if the
FontSize is 0.1 in normalized units,
then the text is 1/10 of the plot box height.
'pixels'

Pixels.

Starting in R2015b, distances in pixels are
independent of your system resolution on Windows® and Macintosh systems:

  • On Windows systems, a pixel is 1/96th of an inch.

  • On Macintosh systems, a pixel is 1/72nd of an inch.

On Linux® systems, the size of a pixel is determined by your system
resolution.

If you set both the font size and the font units in one function call, you must set
the FontUnits property first so that the axes correctly interprets
the specified font size.

Text Box

expand all

EdgeColorColor of box outline
'none' (default) | RGB triplet | hexadecimal color code | 'r' | 'g' | 'b' | …

Color of box outline, specified as an RGB triplet, a hexadecimal color code, a color
name, or a short name.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0 0 1]

Example: '#0000FF'

BackgroundColorColor of text box background
'none' (default) | RGB triplet | hexadecimal color code | 'r' | 'g' | 'b' | …

Color of text box background, specified as an RGB triplet, a hexadecimal color code,
a color name, or a short name.

For a custom color, specify an RGB triplet or a hexadecimal color code.

  • An RGB triplet is a three-element row vector whose elements
    specify the intensities of the red, green, and blue
    components of the color. The intensities must be in the
    range [0,1], for example, [0.4
    0.6 0.7]
    .

  • A hexadecimal color code is a character vector or a string
    scalar that starts with a hash symbol (#)
    followed by three or six hexadecimal digits, which can range
    from 0 to F. The
    values are not case sensitive. Therefore, the color codes
    "#FF8800",
    "#ff8800",
    "#F80", and
    "#f80" are equivalent.

Alternatively, you can specify some common colors by name. This table lists the named color
options, the equivalent RGB triplets, and hexadecimal color codes.

Color Name Short Name RGB Triplet Hexadecimal Color Code Appearance
"red" "r" [1 0 0] "#FF0000"

Sample of the color red

"green" "g" [0 1 0] "#00FF00"

Sample of the color green

"blue" "b" [0 0 1] "#0000FF"

Sample of the color blue

"cyan" "c" [0 1 1] "#00FFFF"

Sample of the color cyan

"magenta" "m" [1 0 1] "#FF00FF"

Sample of the color magenta

"yellow" "y" [1 1 0] "#FFFF00"

Sample of the color yellow

"black" "k" [0 0 0] "#000000"

Sample of the color black

"white" "w" [1 1 1] "#FFFFFF"

Sample of the color white

"none" Not applicable Not applicable Not applicable No color

Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many types of plots.

RGB Triplet Hexadecimal Color Code Appearance
[0 0.4470 0.7410] "#0072BD"

Sample of RGB triplet [0 0.4470 0.7410], which appears as dark blue

[0.8500 0.3250 0.0980] "#D95319"

Sample of RGB triplet [0.8500 0.3250 0.0980], which appears as dark orange

[0.9290 0.6940 0.1250] "#EDB120"

Sample of RGB triplet [0.9290 0.6940 0.1250], which appears as dark yellow

[0.4940 0.1840 0.5560] "#7E2F8E"

Sample of RGB triplet [0.4940 0.1840 0.5560], which appears as dark purple

[0.4660 0.6740 0.1880] "#77AC30"

Sample of RGB triplet [0.4660 0.6740 0.1880], which appears as medium green

[0.3010 0.7450 0.9330] "#4DBEEE"

Sample of RGB triplet [0.3010 0.7450 0.9330], which appears as light blue

[0.6350 0.0780 0.1840] "#A2142F"

Sample of RGB triplet [0.6350 0.0780 0.1840], which appears as dark red

Example: 'blue'

Example: [0 0 1]

Example: '#0000FF'

LineStyleLine style of box outline
'-' (default) | '--' | ':' | '-.' | 'none'

Line style of box outline, specified as one of the options in this
table.

Line Style Description Resulting Line
'-' Solid line

'--' Dashed line

':' Dotted line

'-.' Dash-dotted line

'none' Line is invisible  

LineWidthWidth of box outline
0.5 (default) | scalar numeric value

Width of box outline, specified as a scalar numeric value in
point units. One point equals 1/72 inch.

Example: 1.5

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

MarginSpace around text within the text box
3 (default) | scalar numeric value

The space around the text within the text box, specified as scalar numeric value in
point units.

MATLAB uses the Extent property value plus the
Margin property value to determine the size of the text box.

Example: 8

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Interactivity

expand all

State of visibility, specified as 'on' or 'off', or as
numeric or logical 1 (true) or
0 (false). A value of 'on'
is equivalent to true, and 'off' is equivalent to
false. Thus, you can use the value of this property as a logical
value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Display the object.

  • 'off' — Hide the object without deleting it. You
    still can access the properties of an invisible object.

Context menu, specified as a ContextMenu object. Use this property
to display a context menu when you right-click the object. Create the context menu using
the uicontextmenu function.

Note

If the PickableParts property is set to
'none' or if the HitTest property is set
to 'off', then the context menu does not appear.

Selection state, specified as 'on' or 'off', or as
numeric or logical 1 (true) or
0 (false). A value of 'on'
is equivalent to true, and 'off' is equivalent to
false. Thus, you can use the value of this property as a logical
value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Selected. If you click the object when in
    plot edit mode, then MATLAB sets its Selected property to
    'on'. If the SelectionHighlight
    property also is set to 'on', then MATLAB displays selection handles around the object.

  • 'off' — Not selected.

Display of selection handles when selected, specified as 'on' or
'off', or as numeric or logical 1
(true) or 0 (false). A
value of 'on' is equivalent to true, and 'off' is
equivalent to false. Thus, you can use the value of this property as
a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Display selection handles when the
    Selected property is set to
    'on'.

  • 'off' — Never display selection handles, even
    when the Selected property is set to
    'on'.

Callbacks

expand all

Mouse-click callback, specified as one of these values:

  • Function handle

  • Cell array containing a function handle and additional
    arguments

  • Character vector that is a valid MATLAB command
    or function, which is evaluated in the base workspace (not recommended)

Use this property to execute code when you click the object.
If you specify this property using a function handle, then MATLAB passes
two arguments to the callback function when executing the callback:

  • Clicked object — Access properties of the clicked object from within
    the callback function.

  • Event data — Empty argument. Replace it with the tilde character
    (~) in the function definition to indicate that this
    argument is not used.

For more information on how to use function handles
to define callback functions, see Create Callbacks for Graphics Objects.

Note

If the PickableParts property is set to 'none' or
if the HitTest property is set to 'off',
then this callback does not execute.

Object creation function, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

For more information about specifying a callback as a function handle, cell array, or character vector, see Create Callbacks for Graphics Objects.

This property specifies a callback function to execute when MATLAB creates the object. MATLAB initializes all property values before executing the CreateFcn callback. If you do not specify the CreateFcn property, then MATLAB executes a default creation function.

Setting the CreateFcn property on an existing component has no effect.

If you specify this property as a function handle or cell array, you can access the object that is being created using the first argument of the callback function. Otherwise, use the gcbo function to access the object.

Object deletion function, specified as one of these values:

  • Function handle.

  • Cell array in which the first element is a function handle. Subsequent elements in the cell array are the arguments to pass to the callback function.

  • Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates this expression in the base workspace.

For more information about specifying a callback as a function handle, cell array, or character vector, see Create Callbacks for Graphics Objects.

This property specifies a callback function to execute when MATLAB deletes the object. MATLAB executes the DeleteFcn callback before destroying the
properties of the object. If you do not specify the DeleteFcn
property, then MATLAB executes a default deletion function.

If you specify this property as a function handle or cell array, you can access the object that is being deleted using the first argument of the callback function. Otherwise, use the gcbo function to access the object.

Callback Execution Control

expand all

Callback interruption, specified as 'on' or 'off', or as
numeric or logical 1 (true) or
0 (false). A value of 'on'
is equivalent to true, and 'off' is equivalent to
false. Thus, you can use the value of this property as a logical
value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

This property determines if a running callback can be interrupted. There are two callback
states to consider:

  • The running callback is the currently executing
    callback.

  • The interrupting callback is a callback that tries
    to interrupt the running callback.

MATLAB determines callback interruption behavior whenever it executes a command that
processes the callback queue. These commands include drawnow, figure, uifigure, getframe, waitfor, and pause.

If the running callback does not contain one of these commands, then no interruption
occurs. MATLAB first finishes executing the running callback, and later executes the
interrupting callback.

If the running callback does contain one of these commands, then the
Interruptible property of the object that owns the running
callback determines if the interruption occurs:

  • If the value of Interruptible is
    'off', then no interruption occurs. Instead, the
    BusyAction property of the object that owns the
    interrupting callback determines if the interrupting callback is discarded or
    added to the callback queue.

  • If the value of Interruptible is 'on',
    then the interruption occurs. The next time MATLAB processes the callback queue, it stops the execution of the
    running callback and executes the interrupting callback. After the interrupting
    callback completes, MATLAB then resumes executing the running callback.

Note

Callback interruption and execution behave differently in these situations:

  • If the interrupting callback is a DeleteFcn,
    CloseRequestFcn, or
    SizeChangedFcn callback, then the interruption
    occurs regardless of the Interruptible property
    value.

  • If the running callback is currently executing the
    waitfor function, then the interruption occurs
    regardless of the Interruptible property
    value.

  • If the interrupting callback is owned by a Timer object, then the callback executes according to
    schedule regardless of the Interruptible property
    value.

Note

When an interruption occurs, MATLAB does not save the state of properties or the display. For example, the
object returned by the gca or gcf command might change when
another callback executes.

Callback queuing, specified as 'queue' or 'cancel'. The BusyAction property determines how MATLAB handles the execution of interrupting callbacks. There are two callback states to consider:

  • The running callback is the currently executing callback.

  • The interrupting callback is a callback that tries to interrupt the running callback.

The BusyAction property determines callback queuing behavior only
when both of these conditions are met:

  • The running callback contains a command that processes the callback queue,
    such as drawnow, figure, uifigure, getframe, waitfor, or pause.

  • The value of the Interruptible property of the object
    that owns the running callback is 'off'.

Under these conditions, the BusyAction property of the
object that owns the interrupting callback determines how MATLAB handles the interrupting callback. These are possible values of the
BusyAction property:

  • 'queue' — Puts the interrupting callback in a queue to be processed after the running callback finishes execution.

  • 'cancel' — Does not execute the interrupting callback.

Ability to capture mouse clicks, specified as one of these values:

  • 'visible' — Capture mouse clicks only when
    visible. The Visible property must be set to
    'on'. The HitTest property
    determines if the Text object responds to the click or if an ancestor does.

  • 'all' — Capture mouse clicks regardless of
    visibility. The Visible property can be set to
    'on' or 'off'. The
    HitTest property determines if the Text object responds to
    the click or if an ancestor does.

  • 'none' — Cannot capture
    mouse clicks. Clicking the Text object
    passes the click to the object below it in the current view of the
    figure window, which is typically the axes or the figure. The HitTest property
    has no effect.

If you want an object to be clickable when it is underneath
other objects that you do not want to be clickable, then set the PickableParts property
of the other objects to 'none' so that the click
passes through them.

Response to captured mouse clicks, specified as 'on' or
'off', or as numeric or logical 1
(true) or 0 (false). A
value of 'on' is equivalent to true, and 'off' is
equivalent to false. Thus, you can use the value of this property as
a logical value. The value is stored as an on/off logical value of type matlab.lang.OnOffSwitchState.

  • 'on' — Trigger the
    ButtonDownFcn callback of the Text object. If you have
    defined the ContextMenu property, then invoke the
    context menu.

  • 'off' — Trigger the callbacks for the nearest
    ancestor of the Text object that has one of these:

    • HitTest property set to
      'on'

    • PickableParts property set to a value that
      enables the ancestor to capture mouse clicks

Note

The PickableParts property determines if
the Text object can capture
mouse clicks. If it cannot, then the HitTest property
has no effect.

This property is read-only.

Deletion status, returned as an on/off logical value of type matlab.lang.OnOffSwitchState.

MATLAB sets the BeingDeleted property to
'on' when the DeleteFcn callback begins
execution. The BeingDeleted property remains set to
'on' until the component object no longer exists.

Check the value of the BeingDeleted property to verify that the object is not about to be deleted before querying or modifying it.

Parent/Child

expand all

ParentParent
Figure object

Parent, specified as a Figure object.

The object has no children. You cannot set this property.

Visibility of the object handle in the Children property
of the parent, specified as one of these values:

  • 'on' — Object handle is
    always visible.

  • 'off' — Object handle is invisible at
    all times. This option is useful for preventing unintended
    changes by another function. Set the
    HandleVisibility to
    'off' to temporarily hide the handle
    during the execution of that function.

  • 'callback' — Object handle is visible
    from within callbacks or functions invoked by callbacks, but not
    from within functions invoked from the command line. This option
    blocks access to the object at the command line, but permits
    callback functions to access it.

If the object is not listed in the Children property of the parent, then
functions that obtain object handles by searching the object hierarchy or querying
handle properties cannot return it. Examples of such functions include the
get, findobj, gca, gcf, gco, newplot, cla, clf, and close functions.

Hidden object handles are still valid. Set the root ShowHiddenHandles property
to 'on' to list all object handles regardless of
their HandleVisibility property setting.

Identifiers

expand all

TypeType of graphics object
'subplottext'

This property is read-only.

Type of graphics object, returned as 'subplottext'. Use this
property to find all objects of a given type within a plotting hierarchy, for example,
searching for the type using findobj.

Object identifier, specified as a character vector or string scalar. You can specify a unique Tag value to serve as an identifier for an object. When you need access to the object elsewhere in your code, you can use the findobj function to search for the object based on the Tag value.

User data, specified as any MATLAB array. For example, you can specify a scalar, vector, matrix, cell array, character array, table, or structure. Use this property to store arbitrary data on an object.

If you are working in App Designer, create public or private properties in the app to share data instead of using the UserData property. For more information, see Share Data Within App Designer Apps.

Version History

Introduced in R2018b

expand all

R2020a: UIContextMenu property is not recommended

Setting or getting UIContextMenu property is not recommended. Instead,
use the ContextMenu
property, which accepts the same type of input and behaves the same way as the
UIContextMenu property.

There are no plans to remove the UIContextMenu property, but it is no
longer listed when you call the set, get, or
properties functions on the Text object.

Text Properties

Modifying Properties

You can set and query graphics object properties using the property editor or the set and get commands.

  • The Property Editor is an interactive tool that enables you to see and change object property values.
  • The set and get commands enable you to set and query the values of properties

To change the default value of properties see Setting Default Property Values.

Text Property Descriptions

This section lists property names along with the types of values each accepts. Curly braces { } enclose default values.

BackgroundColor              ColorSpec | {none}

Color of text extent rectangle. This property enables you define a color for the rectangle that encloses the text Extent. For example, the following code creates a text object that labels a plot and sets the background color to light green.

  • text(3*pi/4,sin(3*pi/4),...
           ['sin(3*pi/4) = ',num2str(sin(3*pi/4))],...
           'HorizontalAlignment','center',... 
           'BackgroundColor',[.7 .9 .7]);
    

For additional features, see the following properties:

  • 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 existing text extent rectangle.

See also Drawing Text in a Box in the MATLAB Graphics documentation for an example using background color with contour labels.

BusyAction                   cancel | {queue}

Callback routine interruption. The BusyAction property enables you to control how MATLAB handles events that potentially interrupt executing callback routines. If there is a callback routine executing, subsequently invoked callback routines always attempt to interrupt it. If the Interruptible property of the object whose callback is executing is set to on (the default), then interruption occurs at the next point where the event queue is processed. If the Interruptible property is set to off, the BusyAction property (of the object owning the executing callback) determines how MATLAB handles the event. The choices are:

  • cancel — Discard the event that attempted to execute a second callback routine
  • queue — Queue the event that attempted to execute a second callback routine until the current callback finishes

ButtonDownFcn                string or function handle

Button press callback routine. A callback routine that executes whenever you press a mouse button while the pointer is over the text object. Define this routine as a string that is a valid MATLAB expression or the name of an M-file. The expression executes in the MATLAB workspace.

See Function Handle Callbacks for information on how to use function handles to define the callback function.

Children                     matrix (read only)

The empty matrix; text objects have no children.

Clipping                     on | {off}

Clipping mode. When Clipping is on, MATLAB does not display any portion of the text that is outside the axes.

Color                        ColorSpec

Text color. A three-element RGB vector or one of the predefined names, specifying the text color. The default value for Color is white. See ColorSpec for more information on specifying color.

CreateFcn                    string or function handle

Callback routine executed during object creation. This property defines a callback routine that executes when MATLAB creates a text object. You must define this property as a default value for text. For example, the statement,

  • set(0,'DefaultTextCreateFcn',...
        'set(gcf,''Pointer'',''crosshair'')')
    

defines a default value on the root level that sets the figure Pointer property to a crosshair whenever you create a text object. MATLAB executes this routine after setting all text properties. Setting this property on an existing text object has no effect.

The handle of the object whose CreateFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo.

See Function Handle Callbacks for information on how to use function handles to define the callback function.

DeleteFcn                    string or function handle

Delete text callback routine. A callback routine that executes when you delete the text object (e.g., when you issue a delete command or clear the axes or figure). MATLAB executes the routine before destroying the object’s properties so these values are available to the callback routine.

The handle of the object whose DeleteFcn is being executed is accessible only through the root CallbackObject property, which you can query using gcbo.

See Function Handle Callbacks for information on how to use function handles to define the callback function.

EdgeColor                    ColorSpec | {none}

Color of edge drawn around text extent rectangle. This property enables you to specify the color of a box drawn around the text Extent. For example, the following code draws a red rectangle around text that labels a plot.

  • text(3*pi/4,sin(3*pi/4),...
    'leftarrowsin(t) = .707',...
    'EdgeColor','red');
    

For additional features, see the following properties:

  • BackgroundColor — Color of the rectangle’s interior (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 existing text extent rectangle.

Editing                      on | {off}

Enable or disable editing mode. When this property is set to the default off, you cannot edit the text string interactively (i.e., you must change the String property to change the text). When this property is set to on, MATLAB places an insert cursor at the beginning of the text string and enables editing. To apply the new text string

  1. Press the ESC key.
  2. Clicking in any figure window (including the current figure).
  3. Reset the Editing property to off.

MATLAB then updates the String property to contain the new text and resets the Editing property to off. You must reset the Editing property to on to resume editing.

EraseMode                    {normal} | none | xor | background

Erase mode. This property controls the technique MATLAB uses to draw and erase text objects. Alternative erase modes are useful for creating animated sequences where controlling the way individual objects redraw is necessary to improve performance and obtain the desired effect.

  • normal — Redraw the affected region of the display, performing the three-dimensional analysis necessary to ensure that all objects are rendered correctly. This mode produces the most accurate picture, but is the slowest. The other modes are faster, but do not perform a complete redraw and are therefore, less accurate.
  • none — Do not erase the text when it is moved or destroyed. While the object is still visible on the screen after erasing with EraseMode none, you cannot print it because MATLAB stores no information about its former location.
  • xor — Draw and erase the text by performing an exclusive OR (XOR) with each pixel index of the screen beneath it. When the text is erased, it does not damage the objects beneath it. However, when text is drawn in xor mode, its color depends on the color of the screen beneath it. It is correctly colored only when over axes background Color, or the figure background Color if the axes Color is set to none.
  • background — Erase the text by drawing it in the axes background Color, or the figure background Color if the axes Color is set to none. This damages objects that are behind the erased text, but text is always properly colored.

    Printing with Nonnormal Erase Modes

MATLAB always prints figures as if the EraseMode of all objects is set to normal. This means graphics objects created with EraseMode set to none, xor, or background can look differently on screen than on paper. On screen, MATLAB may mathematically combine layers of colors (e.g., XORing a pixel color with that of the pixel behind it) and ignore three-dimensional sorting to obtain greater rendering speed. However, these techniques are not applied to the printed output.

You can use the MATLAB getframe command or other screen capture application to create an image of a figure containing nonnormal mode objects.

Extent                       position rectangle (read only)

Position and size of text. A four-element read-only vector that defines the size and position of the text string

  • [left,bottom,width,height]
    

If the Units property is set to data (the default), left and bottom are the x and y coordinates of the lower left corner of the text Extent.

For all other values of Units, left and bottom are the distance from the lower left corner of the axes position rectangle to the lower left corner of the text Extent. width and height are the dimensions of the Extent rectangle. All measurements are in units specified by the Units property.

FontAngle                    {normal} | italic | oblique

Character slant. MATLAB uses this property to select a font from those available on your particular system. Generally, setting this property to italic or oblique selects a slanted font.

FontName                     A name, such as Courier, or the string FixedWidth

Font family. A string specifying the name of the font to use for the text object. To display and print properly, this must be a font that your system supports. The default font is Helvetica.

Specifying a Fixed-Width Font

If you want text to use a fixed-width font that looks good in any locale, you should set FontName to the string FixedWidth:

  • set(text_handle,'FontName','FixedWidth')
    

This eliminates the need to hard code the name of a fixed-width font, which may not display text properly on systems that do not use ASCII character encoding (such as in Japan where multibyte character sets are used). A properly written MATLAB application that needs to use a fixed-width font should set FontName to FixedWidth (note that this string is case sensitive) and rely on FixedWidthFontName to be set correctly in the end-user’s environment.

End users can adapt a MATLAB application to different locales or personal environments by setting the root FixedWidthFontName property to the appropriate value for that locale from startup.m.

Note that setting the root FixedWidthFontName property causes an immediate update of the display to use the new font.

FontSize                     size in FontUnits

Font size. An integer specifying the font size to use for text in units determined by the FontUnits property. The default point size is 10 (1 point = 1/72 inch).

FontWeight                   light | {normal} | demi | bold

Weight of text characters. MATLAB uses this property to select a font from those available on your particular system. Generally, setting this property to bold or demi causes MATLAB to use a bold font.

FontUnits                    {points} | normalized | inches |
                              centimeters | pixels

Font size units. MATLAB uses this property to determine the units used by the FontSize property. Normalized units interpret FontSize as a fraction of the height of the parent axes. When you resize the axes, MATLAB modifies the screen FontSize accordingly. pixels, inches, centimeters, and points are absolute units (1 point = 1/72 inch).

HandleVisibility             {on} | callback | off

Control access to object’s handle by command-line users and GUIs. This property determines when an object’s handle is visible in its parent’s list of children. HandleVisibility is useful for preventing command-line users from accidentally drawing into or deleting a figure that contains only user interface devices (such as a dialog box).

Handles are always visible when HandleVisibility is set to on.

Setting HandleVisibility to callback causes handles to be visible from within callback routines or functions invoked by callback routines, but not from within functions invoked from the command line. This provides a means to protect GUIs from command-line users, while allowing callback routines to have complete access to object handles.

Setting HandleVisibility to off makes handles invisible at all times. This may be necessary when a callback routine invokes a function that might potentially damage the GUI (such as evaluating a user-typed string), and so temporarily hides its own handles during the execution of that function.

When a handle is not visible in its parent’s list of children, it cannot be returned by functions that obtain handles by searching the object hierarchy or querying handle properties. This includes get, findobj, gca, gcf, gco, newplot, cla, clf, and close.

When a handle’s visibility is restricted using callback or off:

  • The object’s handle does not appear in its parent’s Children property.
  • Figures do not appear in the root’s CurrentFigure property.
  • Objects do not appear in the root’s CallbackObject property or in the figure’s CurrentObject property.
  • Axes do not appear in their parent’s CurrentAxes property.

You can set the root ShowHiddenHandles property to on to make all handles visible, regardless of their HandleVisibility settings (this does not affect the values of the HandleVisibility properties).

Handles that are hidden are still valid. If you know an object’s handle, you can set and get its properties, and pass it to any function that operates on handles.

HitTest                      {on} | off

Selectable by mouse click. HitTest determines if the text can become the current object (as returned by the gco command and the figure CurrentObject property) as a result of a mouse click on the text. If HitTest is set to off, clicking on the text selects the object below it (which is usually the axes containing it).

For example, suppose you define the button down function of an image (see the ButtonDownFcn property) to display text at the location you click on with the mouse.

First define the callback routine.

  • function bd_function
    pt = get(gca,'CurrentPoint');
    text(pt(1,1),pt(1,2),pt(1,3),...
           '{fontsize{20}oplus} The spot to label',...
           'HitTest','off')
    

Now display an image, setting its ButtonDownFcn property to the callback routine.

  • load earth
    image(X,'ButtonDownFcn','bd_function'); colormap(map)
    

When you click on the image, MATLAB displays the text string at that location. With HitTest set to off, existing text cannot intercept any subsequent button down events that occur over the text. This enables the image’s button down function to execute.

HorizontalAlignment          {left} | center | right

Horizontal alignment of text. This property specifies the horizontal justification of the text string. It determines where MATLAB places the string with regard to the point specified by the Position property. The following picture illustrates the alignment options.

See the Extent property for related information.

Interpreter                  {tex} | none

Interpret Tex instructions. This property controls whether MATLAB interprets certain characters in the String property as Tex instructions (default) or displays all characters literally. See the String property for a list of supported Tex instructions.

Interruptible                {on} | off

Callback routine interruption mode. The Interruptible property controls whether a text callback routine can be interrupted by subsequently invoked callback routines. Text objects have three properties that define callback routines: ButtonDownFcn, CreateFcn, and DeleteFcn. See the BusyAction property for information on how MATLAB executes callback routines.

LineStyle                    {-} | -- | : | -. | none

Edge line type. This property determines the line style used to draw the edges of the text Extent. The available line styles are shown in the following table.

Symbol Line Style
- solid line (default)
-- dashed line
: dotted line
-. dash-dot line
none no line

For example, the following code draws a red rectangle wth a dotted line style around text that labels a plot.

  • text(3*pi/4,sin(3*pi/4),...
         'leftarrowsin(t) = .707',...
         'EdgeColor','red',...
         'LineWidth',2,...
         'LineStyle',':');
    

For additional features, see the following properties:

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

LineWidth                    scalar (points)

Width of line used to draw text extent rectangle. When you set the text EdgeColor property to a color (the default is none), MATLAB displays a rectangle around the text Extent. Use the LineWidth property to specify the width of the rectangle edge. For example, the following code draws a red rectangle around text that labels a plot and specifies a line width of 3 points:

  • text(3*pi/4,sin(3*pi/4),...
    'leftarrowsin(t) = .707',...
    'EdgeColor','red',...
    'LineWidth',3);
    

For additional features, see the following 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)
  • Margin — increase the size of the rectangle by adding a margin to the exsiting text extent rectangle

Margin                       scalar (pixels)

Distance between the text extent and the rectangle edge. When you specify a color for the BackgroundColor or EdgeColor text properties, MATLAB draws a rectangle around the area defined by the text Extent plus the value specified by the Margin. For example, the following code displays a light green rectangle with a 10-pixel margin.

  • text(5*pi/4,sin(5*pi/4),...
           ['sin(5*pi/4) = ',num2str(sin(5*pi/4))],...
           'HorizontalAlignment','center',... 
           'BackgroundColor',[.7 .9 .7],...
           'Margin',10);
    

For additional features, see the following 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)

Parent                       handle

Text object’s parent. The handle of the text object’s parent object. The parent of a text object is the axes in which it is displayed. You can move a text object to another axes by setting this property to the handle of the new parent.

Position                     [x,y,[z]]

Location of text. A two- or three-element vector, [x y [z]], that specifies the location of the text in three dimensions. If you omit the z value, it defaults to 0. All measurements are in units specified by the Units property. Initial value is [0 0 0].

Rotation                     scalar (default = 0)

Text orientation. This property determines the orientation of the text string. Specify values of rotation in degrees (positive angles cause counterclockwise rotation).

Selected                     on | {off}

Is object selected? When this property is set to on, MATLAB displays selection handles if the SelectionHighlight property is also set to on. You can, for example, define the ButtonDownFcn to set this property, allowing users to select the object with the mouse.

SelectionHighlight           {on} | off

Objects highlight when selected. When the Selected property is set to on, MATLAB indicates the selected state by drawing four edge handles and four corner handles. When SelectionHighlight is set to off, MATLAB does not draw the handles.

String                       string

The text string. Specify this property as a quoted string for single-line strings, or as a cell array of strings, or a padded string matrix for multiline strings. MATLAB displays this string at the specified location. Vertical slash characters are not interpreted as linebreaks in text strings, and are drawn as part of the text string. See Mathematical Symbols, Greek Letters, and TeX Characters for an example.

You can also specify stream modifiers that control the font used. The first four modifiers are mutually exclusive. However, you can use fontname in combination with one of the other modifiers:

  • bf — bold font
  • it — italics font
  • sl — oblique font (rarely available)
  • rm — normal font
  • fontname{fontname} — specify the name of the font family to use.
  • fontsize{fontsize} — specify the font size in FontUnits.

Stream modifiers remain in effect until the end of the string or only within the context defined by braces { }.

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: \, {, } _, ^.

See the example in the text reference page for more information.

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

Tag                          string

User-specified object label. The Tag property provides a means to identify graphics objects with a user-specified label. This is particularly useful when constructing interactive graphics programs that would otherwise need to define object handles as global variables or pass them as arguments between callback routines. You can define Tag as any string.

Type                         string (read only)

Class of graphics object. For text objects, Type is always the string 'text'.

Units                        pixels | normalized | inches |
                             centimeters | points | {data}

Units of measurement. This property specifies the units MATLAB uses to interpret the Extent and Position properties. All units are measured from the lower left corner of the axes plotbox.

  • Normalized units map the lower left corner of the rectangle defined by the axes to (0,0) and the upper right corner to (1.0,1.0).
  • pixels, inches, centimeters, and points are absolute units (1 point = 1/72 inch).
  • data refers to the data units of the parent axes.

If you change the value of Units, it is good practice to return it to its default value after completing your computation so as not to affect other functions that assume Units is set to the default value.

UserData                     matrix

User-specified data. Any data you want to associate with the text object. MATLAB does not use this data, but you can access it using set and get.

UIContextMenu                handle of a uicontextmenu object

Associate a context menu with the text. Assign this property the handle of a uicontextmenu object created in the same figure as the text. Use the uicontextmenu function to create the context menu. MATLAB displays the context menu whenever you right-click over the text.

VerticalAlignment            top | cap | {middle} | baseline |
                             bottom

Vertical alignment of text. This property specifies the vertical justification of the text string. It determines where MATLAB places the string with regard to the value of the Position property. The possible values mean

  • top — Place the top of the string’s Extent rectangle at the specified y-position.
  • cap — Place the string so that the top of a capital letter is at the specified y-position.
  • middle — Place the middle of the string at specified y-position.
  • baseline — Place font baseline at the specified y-position.
  • bottom — Place the bottom of the string’s Extent rectangle at the specified y-position.

The following picture illustrates the alignment options.

Visible                      {on} | off

Text visibility. By default, all text is visible. When set to off, the text is not visible, but still exists and you can query and set its properties.

   text   textread 

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить размер шрифта mac os
  • Как изменить размер шрифта latex
  • Как изменить размер шрифта iphone
  • Как изменить размер шрифта gmail
  • Как изменить размер шрифта bootstrap

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии