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

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

Можно изменить размер шрифта, имя и стиль, используемый инструментами в MATLAB®. Также можно установить новые шрифты, чтобы использовать с MATLAB.

Изменение масштаба

Можно изменить уровень изменения масштаба в Редакторе, Live Editor и Браузере документации. Чтобы увеличить и уменьшить масштаб, удержите клавишу Ctrl и переместите колесико прокрутки. В macOS системах используйте ключ Command вместо этого.

В качестве альтернативы можно увеличить и уменьшить масштаб использования доступных горячих клавиш.

Действие Горячая клавиша

Увеличение

Ctrl+Plus

В macOS системах используйте Command+Shift+Plus.

Уменьшение

Ctrl+Minus

В macOS системах используйте Command+Shift+Minus.

Сбросьте изменение масштаба

(Не поддерживаемый в Браузере документации)

Ctrl+Alt+0

В macOS системах используйте Command+Alt+0.

В качестве альтернативы можно изменить уровень изменения масштаба в Редакторе и Live Editor путем движения во вкладку View и выбора
Zoom In,
Zoom Out или
Reset Zoom.

В MATLAB Online™, чтобы изменить уровень изменения масштаба, настраивают настройки изменения масштаба для вашего веб-браузера.

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

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

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

Live Editor

Задайте размер шрифта для кода и текста программно с помощью настроек. Для получения дополнительной информации см. matlab.fonts Настройки.

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

  • Редактор

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

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

Задайте размер шрифта с помощью настроек шрифта.

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

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

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

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

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

Задайте размер шрифта с помощью настроек шрифта.

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

Графики

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

В MATLAB Online только можно изменить размер шрифта для Редактора (использующий настройки шрифта) и Live Editor (использующий настройки).

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

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

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

Live Editor

Задайте название шрифта и стиль для кода и текста программно с помощью настроек. Например, этот код изменяет название шрифта и стиль обычного текста в Live Editor.

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

Для получения дополнительной информации см. matlab.fonts Настройки.

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

  • Редактор

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

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

Задайте название шрифта и стиль с помощью настроек шрифта.

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

По умолчанию шрифт кода собирается в моноширинный сохранить выравнивание по вертикали. Когда шрифт установлен в моноширинный, фактический отображенный шрифт в Редакторе отличается, чем шрифт, отображенный в Командном окне и Истории команд. Это вызвано тем, что моноширинный логический шрифт, не физический шрифт. Чтобы избежать этого несоответствия, задайте название шрифта как физический шрифт, например, Courier New.

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

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

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

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

Задайте название шрифта и стиль с помощью настроек шрифта.

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

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

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

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

В MATLAB Online только можно изменить название шрифта и стиль шрифта для Редактора (использующий настройки шрифта) и Live Editor (использующий настройки).

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

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

Можно далее настроить шрифты в MATLAB путем изменения настроек шрифта для отдельного инструмента. Чтобы изменить настройки шрифта, на вкладке Home, в разделе Environment, нажимают
Preferences. Выберите > > и выберите инструмент из списка Desktop tools. Затем выберите шрифт, чтобы использовать:

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

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

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

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

Установка настроек пользовательского шрифта не поддерживается для Live Editor. Изменить название шрифта и стиль кода и текста в Live Editor, с помощью настроек. Для получения дополнительной информации см. matlab.fonts Настройки.

Настройки стандартного шрифта

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

Инструмент

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

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

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

Desktop code

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

Когда шрифт установлен в моноширинный, фактический отображенный шрифт в Редакторе отличается, чем шрифт, отображенный в Командном окне и Истории команд. Это вызвано тем, что моноширинный логический шрифт, не физический шрифт. Чтобы избежать этого несоответствия, задайте название шрифта как физический шрифт, например, Courier New.

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

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

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

Desktop text

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

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

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

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

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

Custom

Гротесковый шрифт, плоскость, 10 точек

Добавьте новый шрифт

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

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

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

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

Установите свой новый шрифт в месте, где MATLAB ищет шрифты. MATLAB ищет шрифты в этих местоположениях:

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

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

Если вы устанавливаете шрифт с выполнением 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.

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

Поделиться

Ещё вопросы

  • 0GCC не связывает RHash?
  • 0Отображение скрытого значения с помощью селектора идентификаторов
  • 0Кендо UI TreeView добавить новый уровень
  • 0Ошибка при запуске моего проекта Maven с использованием Springmvc и Hibernate
  • 0setInterval () препятствует удобству пользовательского интерфейса, какое-либо исправление?
  • 0объединить две таблицы в файле php
  • 0ASP.NET User Control (ascx) внутри php-файла
  • 1Аутентификация в Microsoft Graph с использованием SPA, а затем использование токена в Web API
  • 1Модульное тестирование Vue — textContent не содержит ожидаемых propsData
  • 0Zend Framework 2 включает
  • 1Шаблон дизайна медиатора: Почему классы должны информировать медиатора о своем поведении?
  • 0Есть ли способы повторно использовать подзапрос в синтаксисе SELECT FROM (запрос) в части JOIN?
  • 1Преобразовать данные буферизованного файла в объект Json: express-fileupload
  • 0разрешить изменение URI в коде воспламенителя
  • 0Как получить доступ к device_vector из функтора
  • 0Как мне постоянно обновлять значение, если оно изменилось в базе данных
  • 0Как я могу проверить, есть ли Angular.js, загруженный на страницу? [Дубликат]
  • 1В Python добавление пустого списка в столбец dataframe с помощью лямбды повышает valueError
  • 0C ++, изменить значения объекта структуры, принадлежащего классу
  • 1CORS не работает с Angular 2 в хром
  • 1Причал отвечает ненужным перенаправлением
  • 1Межпроцессное взаимодействие с модифицированным интерпретатором Python
  • 0Как добавить Zend REST API на существующий сайт Concrete5?
  • 0Подсчитать отличное значение с 2 критериями
  • 1Как принять Ctrl + Enter в качестве возврата при обработке события Enter для текстового поля в WPF?
  • 1Значение приращения из выражения
  • 0OpenCV случайный лес CvRTrees ошибка
  • 0Использование std :: sort с пользовательским объектом сортировки и шаблоном типа данных — Поиск правильного синтаксиса
  • 0Загрузка пользовательских написанных функций в jQuery после загрузки ajax
  • 0Заставить цвет фона моего нижнего колонтитула заполнить окно браузера
  • 1Бросить исключение, если обработчик сообщений потребителя template.convertSendAndReceive выбрасывает исключение?
  • 1разъединенные компоненты, передающие результат c #
  • 1Условно прерванная отладка
  • 0загрузить представление в div с помощью jquery
  • 0Данные формы не отправляются для последующей обработки PHP
  • 1Highcharter — переместить метку данных в верхнюю часть столбца
  • 0Почему Джон Папа использует Object.defineProperty поверх обычной инициализации?
  • 1Файл существует, но файл статуса 404 не найден на главной странице asp.net
  • 1Как вычесть числа из строк, чтобы получить разницу во времени
  • 0PHP Echo информация и ждать, чтобы удалить ее
  • 1ASP.NET Identity — проверка уникального адреса электронной почты пользователя в IdentityUser
  • 1Небольшое недопонимание полиморфизма в Java
  • 1производительность генерации двоичных файлов
  • 1Использование linq для поиска дубликатов в списке <Vector2>
  • 0Каков наилучший способ устранения ошибки ограничения внешнего ключа
  • 1Сохранение ссылки на актерскую систему
  • 0CKEDITOR — используйте клавишу Backspace для выделения текста
  • 1Остановка службы после завершения работы
  • 1Rails will_paginate бесконечная прокрутка с массивом, который отбрасывает первые 3 элемента

Как увеличить / уменьшить масштаб в редакторе Matlab?

Мне интересно, есть ли способ увеличить / уменьшить масштаб или изменить размер шрифта или каким-либо образом сделать текст в коде в редакторе Matlab больше / меньше!

3 ответа

Вы переходите к Home->Preferences->MATLAB->Fonts и можете изменить размер текста. Если вы поиграете с окружающими предпочтениями, вы также сможете персонализировать больше вещей.

В зависимости от вашей версии MATLAB откройте окно «Preferences». По крайней мере, в более новых версиях это обычно находится в верхней части главного окна, на панели с надписью «Environment».

В открывшемся окне перейдите на вкладку «Шрифты». Вверху правой части окна вы найдете раскрывающееся меню, содержащее размер шрифта. Это влияет на размер шрифта в командном окне, редакторе и истории команд. Вы также можете изменить шрифт здесь.

Если кто-то еще задает эти вопросы в сообщении поисковой системы 2017 *: следующий код, по-видимому, увеличивает масштаб всего редактора MATLAB в 1,5 раза, но требует перезапуска MATLAB:

Изменение размера шрифтов в графиках Matlab

Я хочу изменить размер шрифта для xlabel , ylabel , размер оси, размер шрифта легенды a.к. а все сразу, возможно ли это? По умолчанию шрифт Helvetica 10.

есть ли способ изменить это?

Я хочу использовать ‘FontSize’, 14, для x или y метки.

7 ответов

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

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

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

если вы не знаете, есть ли у вас startup.m file, run

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

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

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

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

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

надеюсь, что это помогает.

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

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

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

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

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

How do I change my editor font size in Matlab R2014b?

I’ve recently installed Matlab R2014b and I don’t seem to manage changing the editor’s font size. Can you give me a hint?

1 Answer 1

It’s in Preferences > Matlab > Fonts

enter image description here

Also, you might want to see this post.

user avatar

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

Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.6.1.42269

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

Я хочу изменить размер шрифта для xlabel, ylabel, размер оси, размер шрифта легенды, или все сразу, возможно ли это? По умолчанию шрифт Helvetica 10.

Есть ли способ изменить это?

Я хочу использовать FontSize, 14, для ярлыков x или y .

7 ответов

Лучший ответ

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

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

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


59

sergeyf
11 Июл 2012 в 22:55

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

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


50

Jonas
20 Янв 2012 в 02:58

Можно изменить шрифты по умолчанию, как для осей, так и для другого текста, добавив следующие строки в файл 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

Чтобы знать, где его разместить.


45

Alexandre Chabot
22 Янв 2012 в 03:18

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

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

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

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


9

p8me
9 Мар 2017 в 20:09

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

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

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

axes('FontSize',24);


5

suresh
20 Янв 2012 в 02:53

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

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

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


5

omian
4 Сен 2013 в 15:52

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

Например:

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


4

mbauman
20 Янв 2012 в 03:02

Понравилась статья? Поделить с друзьями:
  • Matlab как изменить масштаб графика
  • Matlab system error
  • Master xl6 ошибка f1
  • Matlab parse error at function
  • Master of orion вылетает после ролика как исправить