Skip to main content

Matplotlib: Mathematical Expressions

Matplotlib allows us to add a subset by using TeX Markup Language. This can help in adding any symbols or any formula to any string on our matplotlib figure including the title, legends, labels and even annotation even fraction also. 

Note: We do not need to install TeX because it gets installed with matplotlib.

Any text element can be used as math text. You can use raw string also and surround the math text with dollar signs ($ ), as in TeX. Regular text and mathtext can be interleaved within the same text. The mathtext font can be selected with the customization variable mathtext.fontset.

Examples

#importing libraries
from matplotlib import pyplot as plt
import numpy as np
x=np.linspace(1,5,100)
y=x
y_1=x**3
y_log=np.log(x)
y_cos=np.cos(np.pi*x)
plt.plot(x,y)
plt.title('gamma>delta')#in case of plain text
plt.show()

Output

gamma

plt.plot(x,y)
plt.title(r'$\gamma>\delta$')# mathematical text
plt.show()

Output

delta

#using subscript in the figure
plt.plot(x,y)
plt.title(r'$y=x_i$')

Output:

subscript

#using superscript in the figure
plt.plot(x,y_1)
plt.title(r'$y=x^3$')

Output:

superscript

# using Fractions
x_1=np.linspace(1,5,10)
y_frac=1+5/(x_1**3)
plt.plot(x_1,y_frac)
plt.title(r'$y=1+\frac{5}{x^3}$',fontsize=30)
plt.show()

Output:

fraction

#using formulas
x_2=np.linspace(1,10,10)
plt.plot(x_2, y_frac)
plt.title(r'$y=\oint\lim_{x\rightarrow\infty}\;1+\frac{5}{x^3}=3$',fontsize=15)
plt.show()

Output:

formula

y_3=np.sqrt(x)
plt.plot(x,y_3)
plt.title(r'$\sqrt[3]{x}$',fontsize=30)
plt.show()

Output:

sqrt

from matplotlib import rc
rc('text', usetex=False) 
plt.plot(x,y_cos)
plt.title(r'$s(x)=\mathcal{\cos(\pi*x)}$',fontsize=15)# calligraphy
plt.show()

Output:

calligraphy

plt.plot(x,y_cos)
plt.title(r'$s(x)=\mathtt{\cos(\pi*x)}$',fontsize=15)# typewriter
plt.show()

Output:

typewriter

#using Accents
plt.plot(x,y_log)
plt.title(r'$\ddot{A}$ ber cool results!')
plt.show()

Output:

accents

Tags
Submitted by devanshi.srivastava on December 10, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.