Matplotlib 简明教程

Matplotlib - LaTeX Text Formatting in Annotations

What is Text formatting in LaTex?

在注释中,在图、图形或绘图中对 LaTeX 文本进行格式化,例如创建的那些。Matplotlib 库可以在注释文本中使用 LaTeX 命令的一个子集来完成。注释有助于为图形中的元素添加说明性标签、说明或注释。

In LaTeX text formatting in annotations within figures, graphs or plots such as those created. Matplotlib library can be accomplished using a subset of LaTeX commands within the annotation text. Annotations help add explanatory labels, descriptions or notes to elements within a graph.

在使用诸如 Matplotlib 之类的工具处理注释中支持 LaTeX 文本渲染时,我们可以使用 LaTeX 命令的子集来格式化这些注释中的文本。这允许在注释中合并样式文本、数学表达式和特殊格式。

When working with tools like Matplotlib that support LaTeX for text rendering in annotations we can use a subset of LaTeX commands to format the text within these annotations. This allows for the incorporation of styled text, mathematical expressions and special formatting within annotations.

LaTeX Formatting in Annotations Includes

以下是注释中的 LaTex 格式。我们逐个看一遍。

The below are the LaTex formatting in Annotations. Let’s see them one by one.

@ {s14} - 数学表达式使用 LaTeX 数学模式表示为分数、希腊字母、上标和下标。

Mathematical Expressions − The mathematical expressions are given as fractions, Greek letters, superscripts and subscripts using LaTeX math mode.

@ {s15} - 文本样式包括使用 LaTeX 命令(如 \textbf{}、\textit{}、\underline{} 和字体大小命令)的粗体、斜体、下划线或不同的字体大小。

Text Styling − The text styling includes bold, italics, underline or different font sizes using LaTeX commands like \textbf{}, \textit{}, \underline{} and font size commands.

@ {s16} - 使用 LaTeX 转义序列转义美元符号、百分比符号或下划线等特殊字符。

Special Characters − Escaping special characters like dollar signs, percentage signs or underscores using LaTeX escape sequences.

@ {s17} - 虽然有限,但使用

Alignment − Control over alignment, though limited, using

\begin{flushleft}...\end{flushleft},
\begin{center}...\end{center},
\begin{flushright}...\end{flushright}.

以上我们已经浏览了 LaTeX 中提供的不同样式格式,现在让我们看看在标注中使用 LaTeX 的文本格式。

In the above we have gone through different styling formats available in LaTex, now let’s see the text formatting in Annotations using LaTex.

LaTeX Text Formatting in Annotations

以下是使用 LaTeX 在标注中进行各种文本格式化的方法。

The below are the various text formatting in Annotations using LaTex.

Basic Text Formatting

可以在标注中使用 LaTeX 命令进行基本的文本格式化。以下是一些命令。

LaTeX commands for basic text formatting can be used in annotations. The following are some.

Bold − 使文本变粗

Bold − To make text bold

\textbf{Bold Text}

Italics − 使文本变斜体

Italics − To make text italic

\textit{Italic Text}

Underline − 给文本添加下划线

Underline − To add an underline to text

\underline{Underlined Text}

Font Size − LaTeX 提供了不同的字体大小命令,例如 \tiny、\small、\large、\Large、\huge、\Huge

Font Size − LaTeX provides different font size commands such as \tiny, \small, \large, \Large, \huge, \Huge

Annotations with Bold text using LaTex

此示例中,我们在标注中使用 LaTeX 文本格式,使绘图上的文本看起来更粗。

Here in this example we are using the LaText text formatting in the Annotations for making the text to look bold on a plot.

Example

import matplotlib.pyplot as plt
# Create a simple plot
x = [1, 2, 3, 4]
y = [2, 5, 7, 10]
plt.plot(x, y, marker='o', linestyle='-')
# Add an annotation with LaTeX text formatting
plt.annotate(r'\textbf{Max Value}',
   xy=(x[y.index(max(y))], max(y)),
   xytext=(2.5, 8),
   arrowprops=dict(facecolor='black', shrink=0.05),
   fontsize=12,
   color='blue',
   bbox=dict(boxstyle='round,pad=0.3', edgecolor='blue', facecolor='lightblue'))
# Set axis labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Example Plot with LaTeX Annotation')
# Show the plot
plt.show()

执行上述代码时,您将获得以下输出 -

On executing the above code you will get the following output −

textformat latex

Mathematical Notation

在 LaTeX 中,数学符号中的文本格式化涉及在数学模式中使用命令和语法,在表达数学内容时为文本元素设置样式。它支持在数学表达式或等式中整合文本格式化功能。

In LaTeX text formatting within mathematical notation involves using commands and syntax within math mode to stylize text elements while expressing mathematical content. It allows for the integration of text formatting features within mathematical expressions or equations.

Basic Text Formatting within Mathematical Notation

数学符号中的基本文本格式如下。

The basic text formatting within the mathematical notations are as follows.

此文本格式使封闭文本在数学表达式中变粗。

This text formatting renders the enclosed text in bold within a mathematical expression.

\mathbf{Bold Text}

斜体文本在数学表达式中以斜体显示封闭文本。

The Italic text displays the enclosed text in italics within a mathematical expression.

\textit{Italic Text}

此文本格式在数学模式中文本以无衬线字体样式显示封闭文本。

This renders the enclosed text in sans-serif font style within math mode.

\textsf{Sans-serif Text}

此文本格式在数学模式下以打字机或等宽字体显示封闭文本。

This displays the enclosed text in a typewriter or monospaced font within math mode.

\texttt{Typewriter Text}

Important points to remember

  1. Text formatting within mathematical notation can be achieved using \text{} or specific formatting commands within math mode.

  2. Some formatting commands may not work in all math environments or may need additional packages or configurations.

  3. LaTeX offers a variety of text formatting options that can be applied within mathematical expressions to enhance the presentation of text-based content.

  4. By utilizing text formatting commands within mathematical notation LaTeX allows for the integration of styled text elements within mathematical expressions by aiding in the clarity and visual appeal of mathematical content.

Subscripts and Superscripts

在 LaTeX 中,下标和上标用于在数学表达式的基线下方或上方放置文本或符号。它们通常用于表示数学符号中的指数、指数或特殊标注。

In LaTeX subscripts and superscripts are used to position text or symbols below subscripts or above superscripts the baseline of a mathematical expression. They’re commonly employed to denote indices, exponents or special annotations within mathematical notation.

Subscripts

下标用于创建下标,在 LaTeX 中我们可以使用下划线 _

Subscripts are used to create a subscript in LaTeX we can use the underscore _.

Superscripts

上标用于创建上标,在 LaTeX 中我们可以使用插入符号 ^

Superscripts to create a superscript in LaTeX we can use the caret ^.

Subscripts and Superscripts usage in Annotation of a plot

在这个示例中,我们使用 LaTex 通过绘图的注解来使用下标和上标用法。

In this example we are using the subscripts and superscripts usage in annotations of a plot by using the LaTex.

import matplotlib.pyplot as plt
# Generating some data points
x = [1, 2, 3, 4]
y = [2, 5, 7, 10]
plt.plot(x, y, 'o-', label='Data')
# Annotating a point with a subscript and a superscript
plt.annotate(r'$\mathrm{Point}_{\mathrm{max}}^{(4, 10)}$',
   xy=(x[y.index(max(y))], max(y)),
   xytext=(3, 8),
   arrowprops=dict(facecolor='black', arrowstyle='->'),
   fontsize=12,
   color='red')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Example Plot with Annotation')
plt.legend()
plt.show()

执行上述代码时,您将获得以下输出 -

On executing the above code you will get the following output −

mathformat latex

Important points to remember

  1. Subscripts and superscripts can be used independently or combined within LaTeX mathematical notation.

  2. They are crucial for denoting variables, indices, exponents and other related mathematical annotations.

  3. LaTeX automatically handles the positioning and sizing of subscripts and superscripts based on the context and surrounding elements within the mathematical expression.

  4. By using subscripts and superscripts in LaTeX we can precisely express mathematical formulas and notations, improving clarity and readability within mathematical content.

Combining Text and Math

在注释中结合文本和数学涉及以连贯且视觉上有效的方式将常规文本和数学表达式嵌入到注释中。

Combining text and math in annotations using LaTeX involves embedding both regular text and mathematical expressions within annotations in a coherent and visually effective manner.

Combining Text and Math using Latex on a plot

在本示例中,我们使用 LaTex 通过注释来结合文本和数学。

Here in this example we are combining the text and math in annotations by using the LaTex.

Example

import matplotlib.pyplot as plt
# Generating some data points
x = [1, 2, 3, 4]
y = [2, 5, 7, 10]
plt.plot(x, y, 'o-', label='Data')
# Annotating a point with combined text and math in LaTeX
plt.annotate(r'$\frac{dx}{dt} = \alpha \cdot x(t) + \beta$ is the differential equation',
   xy=(x[2], y[2]),
   xytext=(2, 6),
   arrowprops=dict(facecolor='black', arrowstyle='->'),
   fontsize=12,
   color='blue')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Example Plot with Annotation by Latex')
plt.legend()
plt.show()

执行上述代码时,您将获得以下输出 -

On executing the above code you will get the following output −

combination math txt

Text Color and Font Styles

在 Matplotlib 中的 LaTeX 注释中,我们可以使用 LaTeX 命令设置文本颜色和字体样式以增强注释的视觉外观。

In LaTeX annotations within Matplotlib we can set text color and font styles using LaTeX commands to enhance the visual appearance of the annotations.

Text Color

要在 LaTeX 注释中设置文本颜色,我们可以使用诸如以下内容的 LaTeX 颜色命令:

To set text color within a LaTeX annotation we can use LaTeX color commands like

\textcolor{color_name}{text}

Font styles

以下是在绘图注释中应用的不同字体样式。

The following are the different font styles applied on an annotation of a plot.

Bold Text − 通过使用命令 \textbf{} 来显示粗体文本。

Bold Text − To display text in bold by using the command \textbf{}.

Italics − 为了显示斜体文本,我们可以使用 \textit{}

Italics − To display the text in italic style we can use \textit{}.

Underline - 如要 подчеркнуть текст, \text мы используем \underline{} .

Underline − To underline the text we use \underline{}.

Combined Usage of text and font styles on annotations

В этом примере мы используем LaTex. \text для смены цвета текста и применения указанного стиля для аннотаций графика.

In this example we are using the LaTex for changing the text color and applying the defined style to the annotations of a plot.

Example

import matplotlib.pyplot as plt
# Generating some data points
x = [1, 2, 3, 4]
y = [2, 5, 7, 10]
plt.plot(x, y, 'o-', label='Data')
# Annotating a point with different text color and font style
plt.annotate(r'\mathbf{\textcolor{red}{Max value:}} \ \textit{\textcolor{blue}{y_{\text{max}} = 10}}',
   xy=(x[y.index(max(y))], max(y)),
   xytext=(3, 8),
   arrowprops=dict(facecolor='black', arrowstyle='->'),
   fontsize=12)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Example Plot with Annotation of color and font style')
plt.legend()
plt.show()

执行上述代码时,您将获得以下输出 -

On executing the above code you will get the following output −

text fontstyle

Important Points to be noted

  1. Ensure that LaTeX is correctly interpreted within Matplotlib annotations by using the r prefix before the string.

  2. Adjust the colors, font styles and other formatting parameters as needed to suit our visualization requirements.

  3. By leveraging LaTeX commands for text color and font styles within Matplotlib annotations we can create visually appealing and informative annotations in our plots. Adjusting these attributes helps in highlighting important information and improving the overall aesthetics of the visualization.

最后,我们可以说通过在 Matplotlib 的注释内使用 LaTeX,我们可以通过允许更清晰和更具信息性的可视化,使用格式化的文本、数学符号和程式化的标签来丰富我们的图表和图像。

Finally we can say by using LaTeX within Matplotlib’s annotations we can enrich our graphs and figures with formatted text, mathematical notations and stylized labels by allowing for clearer and more informative visualizations.

Bold font weight for LaTeX axes label

В этом примере мы устанавливаем для метки оси LaTeX полужирный вес шрифта.

In this example we are setting the LaTex axes label as Bold font weight.

Example

import numpy as np
from matplotlib import pyplot as plt, font_manager as fm
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams["font.fantasy"] = "Comic Sans MS"
x = np.array([1, 2, 3, 4])
y = np.exp(x)
ax1 = plt.subplot()
ax1.set_xticks(x)
ax1.set_yticks(y)
ax1.plot(x, y, c="red")
ax1.set_xticklabels([r"$\bf{one}$", r"$\bf{two}$", r"$\bf{three}$",
   r"$\bf{four}$"], rotation=45)
ax1.set_yticklabels([r"$\bf{:.2f}$".format(y[0]), r"$\bf{:.2f}$".format(y[1]),
   r"$\bf{:.2f}$".format(y[2]), r"$\bf{:.2f}$".format(y[3])], rotation=45)
plt.tight_layout()
plt.show()

执行上述代码时,您将获得以下输出 -

On executing the above code you will get the following output −

bold latex

Format a float using matplotlib’s LaTeX formatter

Здесь, в этом примере, мы форматируем float, используя форматтер Latex от matplotlib.

Here in this example we are formatting a float using matplotlib’s Latex formatter.

Example

import numpy as np
from matplotlib import pyplot as plt
# Set the figures size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# x and y data points
x = np.linspace(-5, 5, 100)
y = x**3/3
# Plot the data points
plt.plot(x, y)
# Fill the area between the curve
plt.fill_between(x, y)
# LaTex representation
plt.title("$area=\int_a^b{x^2dx}$=83.3")
# Display the plot
plt.show()

执行上述代码时,您将获得以下输出 -

On executing the above code you will get the following output −

float latex

Obtain the same font in Matplotlib output as in LaTex output

Здесь, в этом примере, мы форматируем float, используя форматтер Latex от matplotlib.

Here in this example we are formatting a float using matplotlib’s Latex formatter.

Example

import numpy as np
from matplotlib import pyplot as plt
# Set the figures size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# x and y data points
x = np.linspace(-5, 5, 100)
y = x**3/3
# Plot the data points
plt.plot(x, y)
# Fill the area between the curve
plt.fill_between(x, y)
# LaTex representation
plt.title("$area=\int_a^b{x^2dx}$=83.3")
# Display the plot
plt.show()

执行上述代码时,您将获得以下输出 -

On executing the above code you will get the following output −

float latex