Plot Mathematical Expressions in Python using Matplotlib

16 Jun, 2022
For plotting equations we will use two modules Matplotlib.pyplot and Numpy. This module helps you to organize your Python code logically. 
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 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 
Lets start our work with one of the most simplest and common equation Y = X2. 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 librariesimport matplotlib.pyplot as pltimport numpy as np # Creating vectors X and Yx = np.linspace(-2, 2, 100)y = x ** 2 fig = plt.figure(figsize = (10, 5))# Create the plotplt.plot(x, y) # Show the plotplt.show()
Output-  
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.  
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: 
Line Styles  
Markers  
Below is a plot created using some of this modifications: 
Python3
# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating vectors X and Yx = np.linspace(-2, 2, 100)y = x ** 2 fig = plt.figure(figsize = (12, 7))# Create the plotplt.plot(x, y, alpha = 0.4, label ='Y = X2',         color ='red', linestyle ='dashed',         linewidth = 2, marker ='D',         markersize = 5, markerfacecolor ='blue',         markeredgecolor ='blue') # Add a titleplt.title('Equation plot') # Add X and y Labelplt.xlabel('x axis')plt.ylabel('y axis') # Add Text watermarkfig.text(0.9, 0.15, 'Jeeteshgavande30',         fontsize = 12, color ='green',         ha ='right', va ='bottom',         alpha = 0.7) # Add a gridplt.grid(alpha =.6, linestyle ='--') # Add a Legendplt.legend() # Show the plotplt.show()
Output-  
Example 1- Plotting a graph of the function y = Cos(x) with its Taylor polynomials of degree 2 and 4. 
Python3
# Import librariesimport matplotlib.pyplot as pltimport 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 polynomialy2 = 1 - x**2 / 2plt.plot(x, y2, 'r-.', label ='Degree 2') # Plot degree 4 Taylor polynomialy4 = 1 - x**2 / 2 + x**4 / 24plt.plot(x, y4, 'g:', label ='Degree 4') # Add features to our figureplt.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 plotplt.show()
Output-  
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:  
Python3
# Import librariesimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure(figsize = (14, 8)) # Creating histogramsamples = np.random.randn(10000)plt.hist(samples, bins = 30, density = True,         alpha = 0.5, color =(0.9, 0.1, 0.1)) # Add a titleplt.title('Random Samples - Normal Distribution') # Add X and y Labelplt.ylabel('X-axis')plt.ylabel('Frequency') # Creating vectors X and Yx = np.linspace(-4, 4, 100)y = 1/(2 * np.pi)**0.5 * np.exp(-x**2 / 2) # Creating plotplt.plot(x, y, 'b', alpha = 0.8) # Show plotplt.show()
Output-  
 
adnanirshad158
simmytarika5
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python