Matplotlib - LaTeX Text Formatting in Annotations



What is Text formatting in 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.

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

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

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

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

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

Alignment − Control over alignment, though limited, using

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

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

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

Basic Text Formatting

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

Bold − To make text bold

\textbf{Bold Text}

Italics − To make text italic

\textit{Italic Text}

Underline − To add an underline to text

\underline{Underlined Text}

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

Annotations with Bold text using 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()

Output

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

Text Format Latex

Mathematical Notation

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.

Bold Text

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

\mathbf{Bold Text}

Italic Text

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

\textit{Italic Text}

Sans-serif Text

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

\textsf{Sans-serif Text}

Typewriter Text

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

\texttt{Typewriter Text}

Important points to remember

  • Text formatting within mathematical notation can be achieved using \text{} or specific formatting commands within math mode.
  • Some formatting commands may not work in all math environments or may need additional packages or configurations.
  • LaTeX offers a variety of text formatting options that can be applied within mathematical expressions to enhance the presentation of text-based content.
  • 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

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

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

Superscripts

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

Subscripts and Superscripts usage in Annotation of a plot

In this example we are using the subscripts and superscripts usage in annotations of a plot 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 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()
Output

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

Math Format Latex

Important points to remember

  • Subscripts and superscripts can be used independently or combined within LaTeX mathematical notation.
  • They are crucial for denoting variables, indices, exponents and other related mathematical annotations.
  • LaTeX automatically handles the positioning and sizing of subscripts and superscripts based on the context and surrounding elements within the mathematical expression.
  • 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

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

Output

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

Combination Math Text

Text Color and Font Styles

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

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 − To display text in bold by using the command \textbf{}.

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

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

Combined Usage of text and font styles on annotations

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

Output

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

Text Font Style

Important Points to be noted

  • Ensure that LaTeX is correctly interpreted within Matplotlib annotations by using the `r` prefix before the string.
  • Adjust the colors, font styles and other formatting parameters as needed to suit our visualization requirements.
  • 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.

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

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

Output

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

bold_latex

Format a float using matplotlib's LaTeX formatter

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

Output

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

float_latex

Obtain the same font in Matplotlib output as in LaTex output

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

Output

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

float_latex
Advertisements