Plot Mathematical Expressions in Python using Matplotlib
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
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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 librariesimport matplotlib.pyplot as pltimport numpy as np# Creating vectors X and Yx = np.linspace(-2, 2, 100)y = x ** 2fig = 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 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:
Function Description 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
Character Line style – solid line style — dashed line style -. dash-dot line style : dotted line style
Markers
Character Marker . point o circle v triangle down ^ triangle up s square p pentagon * star + plus x cross D diamond
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 ** 2fig = plt.figure(figsize = (12, 7))# Create the plotplt.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 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 npx = 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 npfig = 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-



