Sitemap
Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Understanding Matplotlib Code with LaTeX Annotations: Enhancing Your Plots

3 min readOct 12, 2024

--

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

plt.plot(x, y)
plt.text(np.pi, y[int(len(y)/2) - 1], r'$\sin(x)$')

plt.savefig('Plots/fig_with_latex.png')
plt.clf()

plt.plot(x, y)

plt.text(1, 0.50, r'$E = mc^2$')
plt.text(1, 0, r'$\frac{d}{dx}e^x = e^x$')
plt.text(4, 0.50, r'$\sum_{i=1}^n i = \frac{n(n + 1)}{2}$')
plt.text(4, 0, r'$\int_0^\infty e^{-x^2}dx = \frac{\sqrt{\pi}}{2}$')

plt.savefig('Plots/fig_with_latex_text.png')
plt.clf()

Importing Necessary Libraries

Importing Matplotlib

import matplotlib.pyplot as plt

In this step, we import the matplotlib.pyplot module and assign it an alias plt. This alias makes it easier to call functions within this module to create and manipulate plots.

Importing NumPy

import numpy as np

We also import the NumPy library and give it the alias `np`. NumPy is a powerful mathematical library that we use to handle numerical operations and data generation in our plots.

Generating Data for the Plot

Creating X Values

x = np.linspace(0, 2*np.pi, 100)

Here, we use the np.linspace() function to create 100 evenly spaced data points between 0 and 2*pi. This array represents the x-coordinates for our plot.

Creating Y Values

y = np.sin(x)

The y-coordinates are generated using the sine function applied to each value in the x array. This gives us a sine wave that we can plot.

Plotting the Sine Wave

plt.plot(x, y)

We use plt.plot() to create a line plot of the sine wave with x as the horizontal axis and `y` as the vertical axis.

Adding a LaTeX Annotation

plt.text(np.pi, y[int(len(y)/2) - 1], r'$\sin(x)$')

This line adds a LaTeX-formatted text label to the plot at the coordinate (π, y[..]) (approximately the midpoint of the sine wave). The LaTeX code $\sin(x)$ creates a beautifully rendered mathematical equation on the graph.

Saving the First Figure

plt.savefig('Plots/fig_with_latex.png')
plt.clf()

The plot is saved as an image file named fig_with_latex.png in the specified folder. After saving, plt.clf() clears the figure so we can start fresh for the next plot.

Visualizing First Figure

Figure with latex text

Plotting the Sine Wave Again

plt.plot(x, y)

We re-plot the same sine wave data points on a new figure.

Adding More LaTeX Annotations

plt.text(1, 0.50, r'$E = mc²$')
plt.text(1, 0, r'$\frac{d}{dx}e^x = e^x$')
plt.text(4, 0.50, r'$\sum_{i=1}^n i = \frac{n(n + 1)}{2}$')
plt.text(4, 0, r'$\int_0^\infty e^{-x²}dx = \frac{\sqrt{\pi}}{2}$')

In this step, we add multiple LaTeX-formatted mathematical expressions to the plot at different coordinates:

  • \( E = mc² \): Einstein’s mass-energy equivalence formula.
  • \( \frac{d}{dx}e^x = e^x \: Derivative of the exponential function.
  • \( \sum_{i=1}^n i = \frac{n(n + 1)}{2} \): Formula for the sum of the first n natural numbers.
  • \( \int_0^\infty e^{-x²}dx = \frac{\sqrt{\pi}}{2} \): Integral of a Gaussian function.

These annotations showcase how LaTeX can be used to display complex mathematical formulas directly on the plot. You can see how difficult it is to read them as is…

Saving the Final Figure

plt.savefig('Plots/fig_with_latex_text.png')
plt.clf()

The final plot is saved as fig_with_latex_text.png in the specified folder, and the plot is cleared once again. This ensures that any subsequent plotting commands will not overlap with the current plot.

Visualizing Final Graph

Figure with custom latex

This graph will display the sine wave with multiple mathematical expressions, demonstrating the versatility of LaTeX annotations in Matplotlib.

Conclusion

This example demonstrates how you can use Matplotlib in combination with LaTeX to create plots that are not only visually appealing but also mathematically informative.

Get Someone’s stories in your inbox

Join Medium for free to get updates from this writer.

By leveraging LaTeX within your plots, you can add complex equations and notations directly to your graphs, making them more professional and suitable for academic or technical presentations.

For those who are interested in further exploring my code examples and projects, feel free to visit my Github. To stay updated on my Matplotlib journey, you can also follow me on Twitter.

--

--

Dev Genius
Dev Genius

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development