Matplotlib - Latex



What is LaTeX?

LaTeX is a typesetting system widely used for producing scientific and technical documents, particularly in disciplines such as mathematics, physics, computer science, engineering and academic writing. It's highly regarded for its superior typesetting of complex mathematical equations, scientific notations, and structured text formatting.

Key Aspects of LaTeX

The below are the key aspects of LaTeX.

  • Markup Language − LaTeX is a markup language, meaning it uses commands and tags to format text rather than WYSIWYG which is abbreviated as What You See Is What You Get editors. Users write plain text with embedded commands that specify the structure and formatting.
  • High-Quality Typesetting − LaTeX excels in producing professional-looking documents with precise typographical and typesetting features. It handles complex structures like mathematical formulas, tables, bibliographies and cross-references exceptionally well.
  • Package System − LaTeX offers a vast array of packages that extend its functionality for specific tasks or document types, providing templates, styles and additional features.
  • Free and Open Source − LaTeX is free to use and is supported by a strong open-source community by ensuring continuous development and a rich ecosystem of packages and resources.
  • Components of LaTeX − The LaTex of matplotlib library have the following components. Let’s see each of them in detail.
  • Document Class − The document class specifies the type of document being created and defines its overall structure, layout and formatting. It acts as a template that sets the style and behaviour for the entire document. Different document classes are available to suit various types of documents such as articles, reports, books, presentations and more.
  • Preamble − In LaTeX the preamble is the section of the document that precedes the main content and the \begin{document} command. It is where we define the document settings, load packages, set parameters and configure global settings that apply to the entire document. The preamble acts as a setup area where we prepare LaTeX for processing the main body of the document.
  • Document Body − The document body in LaTeX is the main section where the content of our document resides. It starts after the preamble and the \begin{document} command and continues until the \end{document} command. This section includes the actual text, sections, subsections, equations, figures, tables and any other elements that constitute the core content of the document.

Advantages of LaTeX

The following are the advantages of LaTex.

  • Quality Typesetting − Produces high-quality output, especially for scientific and technical documents.
  • Cross-Referencing − Simplifies referencing and cross-referencing of equations, figures, tables, and sections.
  • Version Control − Facilitates version control and collaboration through plain text-based files.
  • Customization − Allows extensive customization of document styles, layouts and formatting.

Disadvantages of LaTeX

  • Learning Curve − Requires learning its syntax and commands which can be daunting for beginners.
  • Limited WYSIWYG − Lack of immediate visual feedback (WYSIWYG) might be challenging for some users accustomed to graphical editors.

Usage of LaTeX

  • Academic Writing − Academic papers, theses, dissertations
  • Scientific − Scientific reports, articles, and journals
  • Technical Documents − Technical documentation, manuals
  • Presentations − Presentations using tools like Beamer

Basic document structure of the LaTex

Syntax

A basic LaTeX document structure includes −

\documentclass{article}
\begin{document}
\section{Introduction}
This is a simple LaTeX document.
\subsection{Subsection}
Some text in a subsection.
\end{document}

The above code defines a basic article document with a hierarchical structure comprising a section and a subsection.

Writing our own LaTeX preamble

To write our own LaTeX preamble in Matplotlib we can use this example as reference.

Example 1

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-10, 10, 100)
y = np.exp(x)
plt.plot(x, y, color='red', label="$y=e^{x}$")
plt.legend(loc='upper right')
plt.show()

Output

This will generate the following output −

Preamble

Example 2

In this example we are using the Latex formula in the legend of a plot inside a .py file.

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 10, 1000)
y = np.sin(x)
plt.plot(x, y, label=r'$\sin (x)$', c="red", lw=2)
plt.legend()
plt.show()

Output

This will generate the following output −

Py Latex

Put a little more complex equation in the label, for example, label=r'αiπ+1=0'. Now look at the legend at the top-right corner of the plot.

Example 3

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 10, 1000)
y = np.sin(x)
plt.plot(x, y, label=r'$\sin (x)$', c="red", lw=2)
plt.legend(r'αiπ+1=0')
plt.show()

Output

This will generate the following output −

Py Latex

Rendering mathematical expressions

Rendering mathematical expressions in LaTeX involves using LaTeX syntax to write mathematical equations, symbols and formulas. LaTeX provides a comprehensive set of commands and notation to create complex mathematical expressions with precision and clarity.

Importance of LaTeX for Mathematics

  • Precision and Clarity − LaTeX allows precise typesetting of mathematical notation and symbols.
  • Consistency − Maintains consistency in formatting across mathematical documents.
  • Publication-Quality − Produces high-quality mathematical expressions suitable for academic and scientific publications.
  • LaTeX's support for mathematical typesetting makes it a preferred choice for researchers, mathematicians, scientists and academics when writing technical or mathematical documents that require accurate and well-formatted mathematical notation.

LaTeX for Mathematical Expressions

The below are the components of LaTex in Mathematical Expressions.

  • Inline Math Mode − Inline math mode in LaTeX is used to include mathematical expressions within the text of a document. We can use inline math mode by enclosing the mathematical expression between a pair of single dollar signs $...$.
  • Using the inline math mode − In this example the mathematical expression `\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}` is included within the text using inline math mode. The result is that the mathematical expression is rendered within the line of text.

Example

import matplotlib.pyplot as plt
equation = r'$x = \frac{{-b \pm \sqrt{{b^2 - 4ac}}}}{{2a}}$'
plt.text(0.5, 0.5, equation, fontsize=12, ha='center')
plt.axis('off')
plt.show()

Output

This will generate the following output −

Inline Math Mode

Display Math Mode

Display math mode in LaTeX is used to showcase mathematical expressions in a separate block, centered and distinct from the surrounding text. It's commonly used for larger or stand-alone equations that deserve prominence in a document.

To use display math mode in LaTeX we have several options let’s see them one by one.

Double Dollar Sign `$$...$$`

Enclose the mathematical expression between $$ symbols for displayed equations. In the following example we are displaying the given input equation by using the $$..$$

Example
$$
   f(x) = \int_{a}^{b} g(x) \, dx
$$
Output

This will generate the following output −

Double Dollar Sign

The 'equation' Environment

Use the 'equation' environment to create a numbered equation.

Example

\begin{equation}
   f(x) = \int_{a}^{b} g(x) \, dx
   \end{equation}
Output

This will generate the following output −

Double Dollar Sign

Note − The above code lines can be executed in the Jupyter Notebook markdown mode.

Symbols and Operators

In LaTeX we can use a wide range of symbols and operators to represent mathematical notation, expressions and operations. Here are some commonly used symbols and operators along with their LaTeX commands.

  • Greek Letters − Alpha: `\alpha`, Beta: `\beta`, Gamma: `\gamma`, Delta: `\delta` and so on.
  • Arithmetic Operators − Plus: `+`, Minus: `-`, Multiplication: `\times` or `*`, Division: `\div` or `/`
  • Relations and Comparisons − Equals: `=`, Not equals: `\neq`, Less than: `<`, Greater than: `>` and so on.
  • Set Theory − Union: `\cup`, Intersection: `\cap`, Subset: `\subset`, Superset: `\supset` and so on
  • Calculus and Limits − Integral: `\int`, Summation: `\sum`, Limit: `\lim`, Derivative: `\frac{dy}{dx}`
  • Functions − Sine: `\sin`, Cosine: `\cos`, Tangent: `\tan`, Logarithm: `\log`, Exponential: `\exp`
  • Roots and Exponents − Square root: `\sqrt{x}`, Exponent: `x^2`, Subscript: `x_1`, Superscript: `x^i`

Other Notations

  • Fractions − `\frac{numerator}{denominator}`
  • Matrices − `bmatrix`, `pmatrix`, `vmatrix`, etc., using the `amsmath` package
  • Special Symbols − For example, `\infty` for infinity, `\emptyset` for an empty set, etc.

Example

In this example we are using the $..$, to display the symbols and operators in the LaTex of matplotlib library.

import matplotlib.pyplot as plt
import matplotlib as mpl
equation = r'$(\alpha + \beta = \gamma \times \delta)$'
plt.figure(figsize=(6, 3))
plt.text(0.5, 0.5, equation, fontsize=12, ha='center', va='center')
plt.axis('off')
plt.show()
Output

This will display the following equation −

Symbols Operators

By utilizing these LaTeX commands for symbols and operators we can create complex mathematical expressions with precision and clarity in our LaTeX documents.

Fractions

In LaTeX we can easily create fractions, subscripts and superscripts to represent mathematical expressions using specific commands and notation.

To create fractions we can use the `\frac{numerator}{denominator}` command. In this example we are creating the fraction \frac{3}{4} ¾.

Example

import matplotlib.pyplot as plt
import matplotlib as mpl
equation = r'The fraction is $\frac{3}{4}$'
plt.figure(figsize=(6, 3))
plt.text(0.5, 0.5, equation, fontsize=12, ha='center', va='center')
plt.axis('off')
plt.show()
Output

This will generate the following equation −

Fraction

Matrices and Arrays

In LaTeX matrices and arrays are used to represent data in matrix form or to display sets of equations. The array environment is the basic structure for creating matrices and arrays in LaTeX while the matrix environments provided by the amsmath package offer additional functionality and easier syntax for matrices.

Creating Matrices and Arrays

Here are we are creating the arrays and matrices using respective environments.

Using ‘array’ Environment

The ‘array’ environment allows us to create matrices or arrays in LaTeX.

Example
\[
\begin{array}{ccc}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\end{array}
\]
Output

This will generate the following equation −

amsmath

Note − The above code lines can be executed in the Jupyter Notebook markdown mode.

Using ‘amsmath’ Package's ‘matrix’ Environments

The amsmath package provides convenient matrix environments such as matrix, pmatrix, bmatrix, Bmatrix, vmatrix, Vmatrix which simplify the creation of matrices.

Example

\[
\begin{matrix}
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\end{matrix}
\]
Output

This will generate the following equation −

Matrix

Note − The above code lines can be executed in the Jupyter Notebook markdown mode.

Matrix Formatting

Here are going to align the columns of the matrix using the LaTex. In matrices or arrays we can specify column alignment using c for centered, l for left-aligned and r for right-aligned columns within the array environment.

The below is the example of applying the column alignment on a matrix.

Example

\[
\begin{array}{ccc}
1 & 222 & 3 \\
4 & 55555 & 6 \\
7 & 888 & 999999 \\
\end{array}
\]
Output

This will generate the following equation −

Matrix Formatting

Note − The above code lines can be executed in the Jupyter Notebook markdown mode.

Additional Notes

  • Matrices and arrays in LaTeX are enclosed within the \[ ... \] or equation environment to display them as standalone equations.
  • The & symbol separates elements within a row and \\ starts a new row.

LaTeX provides versatile tools for displaying matrices and arrays allowing us to represent mathematical data or equations in matrix form with various alignments and configurations. LaTeX enables the creation of matrices and arrays for mathematical notation.

Example

\begin{bmatrix}
1 & 2 \\
3 & 4
\end{bmatrix}
Output

This will generate the following equation −

Matrix Alignment

Note − The above code lines can be executed in the Jupyter Notebook markdown mode.

Special Functions

LaTeX supports notation for special functions like trigonometric functions, logarithms, etc.

Example

import matplotlib.pyplot as plt

# LaTeX code for the bold text
bold_text = r'$\sin(\theta), \log(x), \lim_{x \to \infty} f(x)$'

# Create a figure and display the bold text
plt.figure(figsize=(6, 3))
plt.text(0.5, 0.5, bold_text, fontsize=12, ha='center', va='center')
plt.axis('off')
plt.show()
Output
Special Functions

Remove random unwanted space in LaTeX-style maths

LaTeX ignores the spaces you type and uses spacing the way it's done in mathematics texts. You can use the following four commands in case you want a different spacing style.

  • \; − thick space
  • \: − medium space
  • \, − a thin space
  • \! − a negative thin space

To remove random unwanted space in LaTeX-style maths in matplotlib plot we can use "\!" which will reduce the extra spacing.

The below is the example of applying the column alignment on a matrix.

Example

from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.subplot(211)
plt.text(0.4, 0.4, r'$\sum_{n=1}^{\infty}\; \frac{-e^{i\pi}}{2^n}!\left[a^2+\delta ^2- \frac{\pi}{2} \right ]$', fontsize=16, color='r')
plt.title("With thick space")
plt.subplot(212)
plt.text(0.4, 0.4, r'$\sum_{n=1}^{\infty}\! \frac{-e^{i\pi}}{2^n}!\left[a^2+\delta ^2- \frac{\pi}{2} \right ]$', fontsize=16, color='r')
plt.title("With thin space")
plt.show()
Output

This will generate the following equation −

space_latex

Notice the difference in spacing after the "Σ (sigma)" symbol. In the first case, we have used thick space (\;) and in the second case, we have used the thin space (\!) to reduce extra spacing.

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}

Note − The above code lines can be executed in the Jupyter Notebook markdown mode.

Italics − To make text italic

\textit{Italic Text}

Note − The above code lines can be executed in the Jupyter Notebook markdown mode.

Underline − To add an underline to text

\underline{Underlined Text}

Note − The above code lines can be executed in the Jupyter Notebook markdown mode.

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

This will generate the following equation −

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

This will generate the following equation −

Math Format Latex

Subscripts and Superscripts

Subscripts and superscripts can be added using the ‘_’ for subscripts and ‘^’ for superscripts. In the following example we are displaying a script content.

Example

import matplotlib.pyplot as plt
import matplotlib as mpl
equation = r'$x_i^2$ denotes $x$ raised to the power of $i$ squared.'
plt.figure(figsize=(6, 3))
plt.text(0.5, 0.5, equation, fontsize=12, ha='center', va='center')
plt.axis('off')
plt.show()
Output

This is will display the following equation −

Subscripts

Nested Subscripts and Superscripts

We can also nest subscripts and superscripts by enclosing the content in curly braces {}. In the example given below we are displaying the nested subscripts.

Example
import matplotlib.pyplot as plt
import matplotlib as mpl
equation = r'$x_{i_j}^{2k}$ represents a nested subscript and superscript.'
plt.figure(figsize=(6, 3))
plt.text(0.5, 0.5, equation, fontsize=12, ha='center', va='center')
plt.axis('off')
plt.show()
Output

The resultant equation is as follows −

Nested Subscripts

Using Commands

For more complex expressions or to ensure consistent formatting we can use commands _ for \subscript{} and ^ for\superscript{} provided by packages like fixltx2e.

Example

In this example we are displaying the complex expressions.

import matplotlib.pyplot as plt
import matplotlib as mpl
equation = r'$x_{i}^{2}$'
plt.figure(figsize=(6, 3))
plt.text(0.5, 0.5, equation, fontsize=12, ha='center', va='center')
plt.axis('off')
plt.show()
Output

The resultant equation is as follows −

Complex Expressions

LaTeX offers straightforward ways to create fractions, subscripts and superscripts, allowing us to represent mathematical expressions accurately and efficiently.

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

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

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

The above code will generate the follwing 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

This will generate the following equation −

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

This will generate the following equation −

float_latex

What is LaTex Rendering?

LaTeX rendering refers to the process of converting LaTeX markup language which contains typesetting instructions and commands, into formatted output. This output is typically high-quality documents, mathematical formulas, scientific papers or technical reports with precise and consistent typography.

LaTeX rendering is widely used in academia, scientific research, technical documentation and publishing due to its robust typesetting capabilities and its ability to produce professional-looking documents.

Key Aspects of LaTeX Rendering

  • Typesetting − LaTeX is renowned for its superior typesetting capabilities ensuring professional-grade document formatting for academic and technical content.
  • Mathematical Formulas − LaTeX is extensively used for its exceptional support in typesetting complex mathematical equations by making it a preferred choice for academic and scientific publications.
  • Markup Language − LaTeX uses a markup language in which, where users write documents with plain text and include commands to specify formatting, structure and content.
  • Compilation − The LaTeX source code needs to be compiled using a LaTeX compiler such as pdflatex, xelatex, lualatex. During compilation the compiler interprets the LaTeX commands and generates the final output in various formats like PDF, DVI or PostScript.
  • Customization − LaTeX allows users to create custom styles, templates and packages by enabling precise control over document formatting and layout.

Benefits of LaTeX Rendering

  • Quality and Consistency − LaTeX ensures high-quality and consistent document formatting across various platforms and devices.
  • Mathematical Typesetting − It excels in handling complex mathematical notation and making it indispensable for scientific and mathematical content.
  • Cross-Platform Compatibility − LaTeX documents can be easily compiled and viewed on different operating systems.
  • Version Control − Plain text-based source files facilitate version control systems by making collaboration and document history management easier.

Enabling Latex Rendering

To enable LaTeX rendering for creating documents, equations or annotations we typically need the following.

  • LaTeX Installation − Install a LaTeX distribution like TeX Live, MiKTeX or MacTeX which includes the necessary LaTeX compiler and packages.
  • Text Editor − Choose a text editor or an integrated development environment (IDE) that supports LaTeX such as TeXstudio, TeXworks, Overleaf or editors like Sublime Text, VS Code or Atom with LaTeX plugins/extensions.
  • Write LaTeX Code − Create a .tex file and write LaTeX code using the appropriate commands and syntax to structure our document which include equations or format text.
  • Compilation − Use the LaTeX compiler to compile the .tex file into the desired output format such as PDF, DVI, PS. Run the appropriate command in the terminal or use the integrated features of our chosen editor/IDE.

Example

For example in a terminal we might run the following code.

pdflatex your_file.tex

Or within an editor/IDE there's often a Build or Compile button to initiate the compilation process.

LaTeX Rendering in Matplotlib for Annotations

For Matplotlib annotations using LaTeX for text formatting within plots we have to ensure the below −

  • Matplotlib Support − Matplotlib supports LaTeX for annotations by using LaTeX syntax within plt.annotate() or similar functions.
  • LaTeX Installation − Ensure we have a working LaTeX installation on our system that Matplotlib can access for rendering LaTeX text within annotations.
  • Correct Syntax − Use the correct LaTeX syntax r'$...$' within Matplotlib functions for annotations to render the desired LaTeX-formatted text.
  • By following the above mentioned steps we can enable LaTeX rendering for various purposes such as document creation, mathematical notation or annotations in visualization libraries like Matplotlib.

Example

In this example we are going to use the LaTex rendering in the annotations of the plot.

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4]
y = [2, 5, 7, 10]
plt.plot(x, y, 'o-', label='Data')

# Annotating a point with LaTeX-rendered text
plt.annotate(r'$\sum_{i=1}^{4} y_i$',   # LaTeX expression within the annotation
   xy=(x[2], y[2]),           # Coordinates of the annotation point
   xytext=(2.5, 6),           # Text position
   arrowprops=dict(facecolor='black', arrowstyle='->'),
   fontsize=12,
   color='green')

# Labeling axes and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Plot with LaTeX rendering in Annotation')
plt.legend()
plt.show()

Output

This will generate the following output −

Image

Example

Here this is another example of using the LaTex rendering in annotations of a plot.

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 LaTeX rendering
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='white',
   bbox=dict(boxstyle='round,pad=0.3', edgecolor='red', facecolor='green'))
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Example Plot with LaTeX Annotation')
plt.legend()
plt.show()

Output

This will generate the following equation −

Image

Axis tick font in a Matplotlib plot using LaTex

Here this is the example to change the axis tick font in matplotlib when rendering using LaTeX

Example

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
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

This will generate the following output −

Axis Tick Latex
Advertisements