Open In App

Plot Mathematical Expressions in Python using Matplotlib

Last Updated : 17 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Matplotlib is a python library used for plotting and visualising, it also allows us to visualize mathematical expressions and functions easily. In this article, we will learn how to plot mathematical expressions in it.

Example 1

Lets start our work with one of the most simple and common equation Y = X². We want to plot 100 points on X-axis. In this case, each and every value of Y is square of X value of the same index and then visualize it.

  • np.linspace(-2, 2, 100): Generates 100 evenly spaced points between -2 and 2 for the x-axis.
  • x ** 2: Squares each element in the x array, creating the y values corresponding to Y = X²
Python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-2, 2, 100)
y = x ** 2

fig = plt.figure(figsize = (10, 5))
plt.plot(x, y)
plt.show()

Output:

plot1
Y = X²

A graph with a blue curve representing a parabolic function is formed.

Example 2

Plotting a graph of the function y = Cos(x)with its Taylor polynomials of degree 2 and 4 around x=0.

  • Degree 2 Taylor Polynomial: 1 - \frac{x^2}{2}
  • Degree 4 Taylor Polynomial: 1 - \frac{x^2}{2} + \frac{x^4}{24}
  • y = np.cos(x): It calculates the cosine of each element in the array x.
  • y2 = 1 - x**2 / 2: This calculates Degree 2 Taylor polynomial approximation of cos⁡(x) centered at x=0.
  • y4 = 1 - x**2 / 2 + x**4 / 24: This calculates Degree 4 Taylor polynomial approximation of cos⁡(x).
Python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-6, 6, 50)

fig = plt.figure(figsize = (14, 8))
y = np.cos(x)
plt.plot(x, y, 'b', label ='cos(x)')
y2 = 1 - x**2 / 2
plt.plot(x, y2, 'r-.', label ='Degree 2')
y4 = 1 - x**2 / 2 + x**4 / 24
plt.plot(x, y4, 'g:', label ='Degree 4')
plt.legend()
plt.grid(True, linestyle =':')
plt.xlim([-6, 6])
plt.ylim([-4, 4])
plt.title('Taylor Polynomials of cos(x) at x = 0')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()

Output:

plot3
Taylor Polynomial

Graph represents three curves with:

  • Blue curve representing y=cos⁡(x)
  • Red dashed curve representing degree 2 Taylor polynomial.
  • Green dotted curve representing degree 4 Taylor polynomial.

Example 3

We will generate an Array of Random Entries and plot a Normal Distribution

  • We will generate 10,000 random samples drawn from a standard normal distribution.
  • We will plot a histogram of these samples.
  • Adding a normal distribution curve using the equation: y = \frac{1}{\sqrt{2\pi}} e^{-x^2/2}  
  • plt.hist(samples, bins=30, density=True, alpha=0.5, color=(0.9, 0.1, 0.1)): This generates a histogram of the data stored in samples, dividing the range of values in samples into 30 bins.
  • x = np.linspace(-4, 4, 100): Generates an array x of 100 evenly spaced values between -4 and 4. These values are used to plot normal distribution curve. This is the range over which the normal distribution is evaluated.
  • y = 1 / (2 * np.pi)**0.5 * np.exp(-x**2 / 2): This defines probability density function (PDF) for the standard normal distribution.
Python
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize = (14, 8))
samples = np.random.randn(10000)
plt.hist(samples, bins = 30, density = True,
         alpha = 0.5, color =(0.9, 0.1, 0.1))
plt.title('Random Samples - Normal Distribution')
plt.ylabel('X-axis')
plt.ylabel('Frequency')
x = np.linspace(-4, 4, 100)
y = 1/(2 * np.pi)**0.5 * np.exp(-x**2 / 2)
plt.plot(x, y, 'b', alpha = 0.8)
plt.show()

Output: 

plot4
Random Samples Normal Distribution

This visualization allows you to compare empirical distribution (histogram) of the random samples with normal curve.

Example 4

Plotting y=sin⁡(x) and its Derivative y′=cos⁡(x) 

  • np.linspace(): Generates 100 evenly spaced points between -2π and 2π. This is the range over which we are plotting the sine and cosine functions.
  • y = np.sin(x): This computes the sine of each element in the x array. The np.sin() function takes an array of values and applies the sine function to each of them. So, y is an array of sine values corresponding to the x values.
  • y_prime = np.cos(x): This computes derivative of the sine function which is the cosine function. Derivative of sin⁡(x) is cos⁡(x) and the np.cos()function calculates the cosine of each value in the x array.
Python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y = np.sin(x)
y_prime = np.cos(x)

fig = plt.figure(figsize=(14, 8))
plt.plot(x, y, 'r-', label='y = sin(x)')
plt.plot(x, y_prime, 'b--', label="y' = cos(x)")
plt.legend()
plt.grid(True, linestyle=':')
plt.xlim([-2 * np.pi, 2 * np.pi])
plt.ylim([-1.5, 1.5])
plt.title('Plot of y = sin(x) and its Derivative y\' = cos(x)')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()

Output:

derivative-of-cos-x
Plotting y=sin⁡(x) and its Derivative y′=cos⁡(x) 
  • A red solid curve representing y=sin⁡(x)
  • A blue dashed curve representing y′=cos⁡(x), which is the derivative of sin⁡(x).

Example 5

Plotting y = e^{-x^2} i.e Gaussian Function.

  • x = np.linspace(-5, 5, 100): This generates an array of 100 evenly spaced points between -5 and 5 (interval you want to plot over). This range will represent x-axis of the plot.
  • np.exp(): This function computes exponential of each element in the array so that this creates the Gaussian shape (bell curve).
Python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-5, 5, 100)
y = np.exp(-x**2)

fig = plt.figure(figsize=(14, 8))
plt.plot(x, y, 'g-', label='y = e^{-x^2}')
plt.legend()
plt.grid(True, linestyle=':')
plt.xlim([-5, 5])
plt.ylim([0, 1])
plt.title('Plot of y = e^{-x^2} (Gaussian Function)')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.show()

Output:

gaussian-function
Plotting y = e^{-x^2} (Gaussian Function)

It represents Gaussian function in green solid curve. These visualizations helps us understand these complex concepts easily. We can aslo plot more mathematical equations like the one discussed above.


Next Article
Article Tags :
Practice Tags :

Similar Reads