The Wayback Machine - https://web.archive.org/web/20250131100827/https://www.geeksforgeeks.org/how-to-calculate-and-plot-the-derivative-of-a-function-using-matplotlib-and-python/
Open In App

How to calculate and plot the derivative of a function using matplotlib and python?

Last Updated : 06 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to learn how to calculate and plot the derivative of a function using Matplotlib in Python.

In our higher standard in school, we all have studied derivatives in the mathematics syllabus of calculus and we know that calculus is a fundamental branch that deals with the study of rates of change and slopes of curves. The derivative of a function measures the rate at which a function changes with respect to its independent variable. In this article, we will learn to calculate the derivative of a function and then plot that derivative of a function using the Matplotlib library in Python.

Numerical Differentiation using Python

Here, we are going to determine the derivative of a function using Python. There are different ways to calculate the derivative of a function in Python, and here we are going to use the NumPy library to derive the derivative of a function. NumPy is used to perform numerical computation in Python and provides functions for numerical differentiation also. The formula for the numerical differentiation can be written as:

[Tex]f'(x)=\displaystyle \lim_{h \to 0}\frac{f(x+h) – f(x)}{h}[/Tex]

Python3

# Import numpy library
import numpy as np
  
# Define a function
def f(x): return x**2 + x
  
# Define the range of x values
x = np.linspace(-5, 5, 100)
  
# Define the step size
h = 0.01
  
# Using central difference formula
# to Calculate the derivative
cal_derivative = (f(x+h) - f(x-h))/(2*h)
  
# Print the derivative values
print(cal_derivative)

                    

Output:

[-9. -8.7979798 -8.5959596 -8.39393939 -8.19191919 -7.98989899 -7.78787879 -7.58585859 -7.38383838 -7.18181818 -6.97979798 -6.77777778 -6.57575758 -6.37373737 -6.17171717 -5.96969697 -5.76767677 -5.56565657 -5.36363636 -5.16161616 -4.95959596 -4.75757576 -4.55555556 -4.35353535 -4.15151515 -3.94949495 -3.74747475 -3.54545455 -3.34343434 -3.14141414 -2.93939394 -2.73737374 -2.53535354 -2.33333333 -2.13131313 -1.92929293 -1.72727273 -1.52525253 -1.32323232 -1.12121212 -0.91919192 -0.71717172 -0.51515152 -0.31313131 -0.11111111 0.09090909 0.29292929 0.49494949 0.6969697 0.8989899 1.1010101 1.3030303 1.50505051 1.70707071 1.90909091 2.11111111 2.31313131 2.51515152 2.71717172 2.91919192 3.12121212 3.32323232 3.52525253 3.72727273 3.92929293 4.13131313 4.33333333 4.53535354 4.73737374 4.93939394 5.14141414 5.34343434 5.54545455 5.74747475 5.94949495 6.15151515 6.35353535 6.55555556 6.75757576 6.95959596 7.16161616 7.36363636 7.56565657 7.76767677 7.96969697 8.17171717 8.37373737 8.57575758 8.77777778 8.97979798 9.18181818 9.38383838 9.58585859 9.78787879 9.98989899 10.19191919 10.39393939 10.5959596 10.7979798 11. ]

Now let’s plot the function and its derivative on the same plot.

Python3

# Importing required libraries
import matplotlib.pyplot as plt
  
# Plot the function and its derivative
plt.plot(x, f(x), label='f(x)')
plt.plot(x, cal_derivative, label="f'(x)")
plt.legend()
plt.show()

                    

Output:

The plot of the function and its derivative on the same graph

The plot of the function and its derivative on the same graph

Sympy Library to Calculate Derivative

As we have seen earlier the method of numerical differentiation which require a bit of mathematical knowledge and the know-how of the formula to use it. To exclude this complexity there are multiple libraries that already have utility functions that can calculate the derivative of any function if it is derivable.

Let’s see how can we use sympy library in python to calculate the derivative of the same above function.

Syntax:

Sympy.diff(function, variable, order)

where,

  • function – This can be a mulivariate function/expression as well
  • variable – It should be that sympy variable with respect to which you would like to differentiate the expression
  • order – Whether we want to calculate the first second or third or so on derivative is defined in here.

R

def f(x): return x**3 - 2*x**2 + 3*x - 1
  
import sympy as sy
x = sy.Symbol('x')
def h(x): return sy.diff(f(x), x)
h(x)

                    

Output:

3x2 - 4x + 3

Partial Derivatives Calculation using Sympy

We can also solve multivariate differentiation using this function as well for example let’s calculate the partial derivatives of the function:

f(x, y) = x3 - 2y2 + 3xy - 1

Python3

import sympy as sy
x = sy.Symbol('x')
y = sy.Symbol('y')
  
def f(x, y): return x**3 - 2*y**2 + 3*y*x - 1
def g(x, y): return sy.diff(f(x, y), x)
def h(x, y): return sy.diff(f(x, y), y)
  
print("Partial Derivative with respect to x: ", g(x, y))
print("Partial Derivative with respect to y: ", h(x, y))

                    

Output:

Partial Derivative with respect to x: 3*x**2 + 3*y Partial Derivative with respect to y: 3*x - 4*y

Scipy Library to Calculate Derivative and Plotting

Scipy library also provides utility functions to perform differentiation of functions. This function is available in scipy.misc. Let’s look at an example of the same on the function f(x) = x3 – 2x2 + 3x – 1.

Python3

from scipy.misc import derivative
def f(x): return x**3 - 2*x**2 + 3*x - 1
derivative(f, 1, dx=0.0001)

                    

Output:

2

Now let’s plot the function and its derivative on the same plot.

Python3

xs = np.linspace(-5, 5, 100)
  
plt.plot(xs, f(xs))
plt.plot(xs, derivative(f, xs, dx=0.001))
plt.legend(["f(x)", "f'(x)"])
plt.show()

                    

Output:

Graph of the function and its derivative on the same plot

Graph of the function and its derivative on the same plot



Similar Reads

three90RightbarBannerImg