Plot Mathematical Expressions in Python using Matplotlib
Last Updated :
17 Apr, 2025
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:
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:
Taylor PolynomialGraph 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, di
viding 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:
Random Samples Normal DistributionThis 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():
G
enerates 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:
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:
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.
Similar Reads
Multiplots in Python using Matplotlib Matplotlib is a Python library that can be used for plotting graphs and figures. Plotting multiplots or multiple plots are often required either for comparing the two curves or show some gradual changes in the multiple plots, and this can be done using Subplots. Subplots are one of the most importan
3 min read
How to Plot Mfcc in Python Using Matplotlib? Mel-frequency cepstral coefficients (MFCC) are widely used in audio signal processing and speech recognition tasks. They represent the spectral characteristics of an audio signal and are commonly used as features for various machine-learning applications. In this article, we will explore how to comp
2 min read
Simple Plot in Python using Matplotlib Creating simple plots is a common step in data visualization. These visual representations help us to understand trends, patterns and relationships within data. Matplotlib is one of the most popular plotting libraries in Python which makes it easy to generate high-quality graphs with just a few line
4 min read
Matplotlib.axes.Axes.plot() in Python Axes.plot() method in Matplotlib is used to plot data on a set of axes. It is primarily used for creating line plots but can be extended for other types of plots, including scatter plots, bar plots, and more. When using this function, you typically provide the x and y coordinates of the data points
3 min read
Matplotlib.pyplot.axes() in Python axes() method in Matplotlib is used to create a new Axes instance (i.e., a plot area) within a figure. This allows you to specify the location and size of the plot within the figure, providing more control over subplot layout compared to plt.subplot(). It's key features include:Creates a new Axes at
3 min read
Matplotlib.pyplot.axis() in Python axis() function in Matplotlib is used to get or set properties of the x- and y-axis in a plot. It provides control over axis limits, aspect ratio and visibility, allowing customization of the plotâs coordinate system and view. It's key feature includes:Gets or sets the axis limits [xmin, xmax, ymin,
3 min read
Change plot size in Matplotlib - Python Plots are an effective way of visually representing data and summarizing it beautifully. However, if not plotted efficiently it seems appears complicated. Python's Matplotlib provides several libraries for data representation. While making a plot we need to optimize its size. In this article, we wil
3 min read
Plotting Sine and Cosine Graph using Matplotlib in Python Data visualization and Plotting is an essential skill that allows us to spot trends in data and outliers. With the help of plots, we can easily discover and present useful information about the data. In this article, we are going to plot a sine and cosine graph using Matplotlib in Python. Matplotlib
3 min read
Matplotlib.pyplot.sci() in Python Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot,
2 min read
Matplotlib.pyplot.axvline() in Python Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python. Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and various graphical user interface toolkits like Tkinter, awxPython, etc. Note: For more inform
3 min read