How to write text in subscript in the axis labels and the legend using Matplotlib?

To write text in subscript in axis labels and legends, we can use LaTeX-style formatting in Matplotlib. The $ symbols enable mathematical notation where _{text} creates subscript text.

Basic Subscript Syntax

Matplotlib uses LaTeX syntax for mathematical notation ?

  • Wrap text in $ symbols to enable LaTeX mode

  • Use _{subscript} for subscript text

  • Use ^{superscript} for superscript text

  • Combine with regular text using raw strings (r'string')

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.linspace(1, 10, 1000)
y = np.exp(x)

plt.plot(x, y, label=r'$e^x$', c="red", lw=2)
plt.xlabel("$X_{axis}$")
plt.ylabel("$Y_{axis}$")
plt.legend(loc='upper left')
plt.show()

Advanced Subscript Examples

You can create more complex subscript formatting ?

import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))

# Example 1: Multiple subscripts
x = np.linspace(0, 10, 100)
y1 = x**2
y2 = x**3

ax1.plot(x, y1, label=r'$H_2O$', color='blue')
ax1.plot(x, y2, label=r'$CO_2$', color='green')
ax1.set_xlabel(r'$X_{data}$ values')
ax1.set_ylabel(r'$Y_{result}$ values')
ax1.legend()
ax1.set_title('Chemical Formulas with Subscripts')

# Example 2: Complex mathematical notation
theta = np.linspace(0, 2*np.pi, 100)
r1 = np.sin(theta)
r2 = np.cos(theta)

ax2.plot(theta, r1, label=r'$\sin(\theta_{max})$')
ax2.plot(theta, r2, label=r'$\cos(\theta_{min})$')
ax2.set_xlabel(r'$\theta_{angle}$ (radians)')
ax2.set_ylabel(r'$f(\theta_{input})$')
ax2.legend()
ax2.set_title('Mathematical Functions with Subscripts')

plt.tight_layout()
plt.show()

Common Subscript Use Cases

Purpose Syntax Example
Variable indices r'$X_{index}$' $X_1$, $X_2$
Chemical formulas r'$H_2O$' $H_2O$, $CO_2$
Mathematical notation r'$\theta_{max}$' $\theta_{max}$, $f_{min}$
Units r'$m_{total}$ (kg)' Mass in kilograms

Key Points

  • Always use raw strings (r'') to prevent backslash escaping

  • Enclose mathematical text in $ symbols

  • Use curly braces {} for multi-character subscripts

  • Combine subscripts and superscripts: r'$x_1^2$'

Conclusion

Use LaTeX syntax with $_{subscript}$ formatting in Matplotlib labels and legends. Raw strings prevent escape character issues and enable clean mathematical notation in your plots.

Updated on: 2026-03-25T19:49:56+05:30

41K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements