Superscript in Python Matplotlib Plots

Muhammad Maisam Abbas Oct 29, 2021
Superscript in Python Matplotlib Plots

This tutorial will discuss writing superscripts in plots using the dollar sign in Python.

Write Superscript in Matplotlib Plots Using the Dollar Sign

We use Matplotlib to plot graphs in Python. Sometimes, we need to add labels to the plot, which include subscripts or superscripts. The Matplotlib also provides a way to write subscripts or superscripts using the dollar sign. To make subscripts, you have to write the expression inside the dollar sign using the _ and ^ symbols. If you use the _ symbol, the superscript will be under the character. If you use the ^ symbol, the superscript will be over the character. For example, let’s create a plot using the Matplotlib and add superscripts using the dollar sign. See the code below.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r"$e^{-t}$", xlabel=r"$time_s$", ylabel=r"$m^2$")
plt.show()

Output:

matplotlib superscript 1

As you can see in the plot, the -t is above the character e because we used the ^ symbol, and the s is below the string time because we used the _ symbol. If the subscript or superscript consists of more than one character, you have put the superscript inside the curly brackets {} otherwise; only the first character will be in the superscript or subscript. For example, we have used curly brackets in the plot title because the superscript has two characters. If you want to put special symbols in the plot, like the alpha or pie symbol, you can use the pre-defined symbols in Matplotlib. To use the symbols, you have to write the symbol name along with a backslash. For example, let’s put some special symbols like pie and alpha in the above graph. See the code below.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r"$\alpha^{-t}$", xlabel=r"$\tau_s$", ylabel=r"$\pi^2$")
plt.show()

Output:

matplotlib superscript 2

As you can see in the plot, there are alpha, pie, and tau symbols. Make sure to use the correct symbol name along with the backslash; otherwise, there will be an error. If you want the superscripted text to be in the same font as the rest of the text, use \mathregular. Check this link to find all the supported symbols and more information about the subscripts and superscripts.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn