Plotting mathematical expression using matplotlib in Python

Aim:

We will use two basic modules:

1.Matplotlib.pyplot(for plotting graphs)

2.Numpy(for creating sample array)

What is Matplotlib.pyplot?

pip install matplotlib

Plot Y = X² using matplotlib in Python

But first, let’s start our work with one of the basic equation Y = X². Let plot 100 points on the  X-axis. In this scenario, every value of Y is a square of the X value at the same index.

# Importing the libraries 
import matplotlib.pyplot as plt
 
import numpy as np 
  
# Creating vectors X and Y 
x = np.linspace(-2, 2, 100) 
y = x**2
  
fig = plt.figure(figsize = (10, 5)) 
# Create the plot 
plt.plot(x, y) 
  
# Show the plot 
plt.show()

Plotting mathematical expression using matplotlib in Python

NOTE: The number of points that we use is being used entirely arbitrarily, but the goal here is to show a smooth graph for a smooth curve and so we have to choose a sufficient number based on the function. But be careful to generate too many points because a large number of points will require a long time to plot.

Plot parabola using matplotlib in Python

A plot is created using some modifications below:

# Import libraries
import matplotlib.pyplot as plt
import numpy as np
  
# Createing vectors X and Y
x = np.linspace(-2, 2, 100)
y = x ** 2
  
fig = plt.figure(figsize = (12, 7))
# Create the plot
plt.plot(x, y, alpha = 0.4, label ='Y = X²',
         color ='red', linestyle ='dashed',
         linewidth = 2, marker ='D', 
         markersize = 5, markerfacecolor ='blue',
         markeredgecolor ='blue')
  
# Add a title
plt.title('Equation plot')
  
# Add X and y Label
plt.xlabel('x axis')
plt.ylabel('y axis')
  
# Add Text watermark
fig.text(0.9, 0.15, 'Code Speedy', 
         fontsize = 12, color ='green',
         ha ='right', va ='bottom', 
         alpha = 0.7)
  
# Add a grid
plt.grid(alpha =.6, linestyle ='--')
  
# Add a Legend
plt.legend()
  
# Show the plot
plt.show()

Output- 

Plotting parabola expression using matplotlib in Python

y= cos(x) plotting using matplotlib in Python

Plotting a graph of the function y = Cos (x) with its polynomial 2 and 4 degrees.

# Import libraries 
import matplotlib.pyplot as plt 
import numpy as np 

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

fig = plt.figure(figsize = (14, 8)) 

# Plot y = cos(x) 
y = np.cos(x) 
plt.plot(x, y, 'b', label ='cos(x)') 

# Plot degree 2 Taylor polynomial 
y2 = 1 - x**2 / 2
plt.plot(x, y2, 'r-.', label ='Degree 2') 

# Plot degree 4 Taylor polynomial 
y4 = 1 - x**2 / 2 + x**4 / 24
plt.plot(x, y4, 'g:', label ='Degree 4') 

# Add features to our figure 
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') 

# Show plot 
plt.show() 

 

Output

y= cos(x) plotting using matplotlib in Python

Let’s take another example-

What about creating an array of 10000 random entries, sampling involving the normal distribution, and creating a histogram with a normal distribution of the equation:

y=1 ∕ √2πe-x^2/2

# Import libraries 
import matplotlib.pyplot as plt 
import numpy as np 
  
fig = plt.figure(figsize = (14, 8)) 
  
# Creating histogram 
samples = np.random.randn(10000) 
plt.hist(samples, bins = 30, density = True, 
         alpha = 0.5, color =(0.9, 0.1, 0.1)) 
  
# Add a title 
plt.title('Random Samples - Normal Distribution') 
  
# Add X and y Label 
plt.ylabel('X-axis') 
plt.ylabel('Frequency') 
  
# Creating vectors X and Y 
x = np.linspace(-4, 4, 100) 
y = 1/(2 * np.pi)**0.5 * np.exp(-x**2 / 2) 
  
# Creating plot 
plt.plot(x, y, 'b', alpha = 0.8) 
  
# Show plot 
plt.show()

 

Output

Normal distribution using matplotlib in Python

Leave a Reply

Your email address will not be published. Required fields are marked *