Open In App

Plot Mathematical Expressions in Python using Matplotlib

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

For plotting equations we will use two modules Matplotlib.pyplot and Numpy. This module helps you to organize your Python code logically.
 

Numpy


Numpy is a core library used in Python for scientific computing. This Python library supports you for a large, multidimensional array object, various derived objects like matrices and masked arrays, and assortment routines that makes array operations faster, which includes mathematical, logical, basic linear algebra, basic statistical operations, shape manipulation, input/output, sorting, selecting, discrete Fourier transforms, random simulation and many more operations.
Note: For more information, refer to NumPy in Python
 

Matplotlib.pyplot


Matplotlib is a plotting library of Python which is a collection of command style functions that makes it work like MATLAB. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits. Each #pyplot# function creates some changes to the figures i.e. creates a figure, creating a plot area in the figure, plotting some lines in the plot area, decoration of the plot with some labels, etc. 
Note: For more information, refer to Pyplot in Matplotlib
 

Plotting the equation


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

Python3

# Import 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()

                    

Output- 
 

Plot Mathematical Expressions in Python using Matplotlib


Here note that the number of points we are using in line plot(100 in this case) is totally arbitrary but the goal here is to show a smooth graph for a smooth curve and that’s why we have to pick enough numbers depending on the function. But be careful that do not generate too many points as a large number of points will require a long time for plotting. 
 

Customization of plots


There are many pyplot functions are available for the customization of the plots, and may line styles and marker styles for the beautification of the plot.Following are some of them:
 

FunctionDescription
plt.xlim()sets the limits for X-axis
plt.ylim()sets the limits for Y-axis
plt.grid()adds grid lines in the plot
plt.title()adds a title
plt.xlabel()adds label to the horizontal axis
plt.ylabel()adds label to the vertical axis
plt.axis()sets axis properties (equal, off, scaled, etc.)
plt.xticks()sets tick locations on the horizontal axis
plt.yticks()sets tick locations on the vertical axis
plt.legend()used to display legends for several lines in the same figure
plt.savefig()saves figure (as .png, .pdf, etc.) to working directory
plt.figure()used to set new figure properties


Line Styles 
 

CharacterLine style
solid line style
dashed line style
-.dash-dot line style
:dotted line style 
 


Markers 
 

CharacterMarker
.point
ocircle
vtriangle down
^triangle up
ssquare
ppentagon
*star
+plus
xcross
Ddiamond


Below is a plot created using some of this modifications:
 

Python3

# Import 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 = (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, 'Jeeteshgavande30',
         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- 
 

Plot Mathematical Expressions in Python using Matplotlib


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

Python3

# 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- 
 

Plot Mathematical Expressions in Python using Matplotlib


Example 2- 
Generating an array of 10000 random entries sampled from normal distribution and creating a histogram along with a normal distribution of the equation: 
y = \frac{1}{\sqrt{2\pi}} e^{-x^2/2}
 

Python3

# 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- 
 

Plot Mathematical Expressions in Python using Matplotlib


 



Last Updated : 16 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads