How to Calculate and Plot the Derivative of a Function Using Python – Matplotlib?

The derivative of a function is one of the key concepts used in calculus. It measures how much a function changes as its input changes, representing the slope of the tangent line at any point.

While Matplotlib is a powerful plotting library for Python, it doesn't provide direct methods to calculate derivatives. Instead, we use NumPy to calculate derivatives and Matplotlib to visualize the results.

What is the Derivative of a Function?

A derivative represents the instantaneous rate of change of a function with respect to its input. Mathematically, the derivative of function f(x) is defined as ?

f'(x) = lim (h ? 0) [(f(x + h) ? f(x)) / h]

This limit gives us the slope of the tangent line at any point x, which is useful for finding maxima, minima, and critical points.

Basic Method Using numpy.gradient()

NumPy's gradient() function calculates the numerical derivative by approximating the gradient of an array. Here's the step-by-step process ?

import numpy as np
import matplotlib.pyplot as plt

# Define the function f(x) = x^2
def f(x):
    return x**2

# Create x values
x = np.linspace(-2, 2, 100)

# Calculate the derivative using gradient
y = f(x)
dfdx = np.gradient(y, x)

# Plot both function and derivative
plt.figure(figsize=(8, 6))
plt.plot(x, y, 'b-', label='f(x) = x²', linewidth=2)
plt.plot(x, dfdx, 'r--', label="f'(x) = 2x", linewidth=2)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Function and Its Derivative')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Example with Trigonometric Function

Let's calculate and plot the derivative of sin(x) ?

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.sin(x)

x = np.linspace(-np.pi, np.pi, 1000)
y = f(x)
dfdx = np.gradient(y, x)

plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', label='f(x) = sin(x)', linewidth=2)
plt.plot(x, dfdx, 'r--', label="f'(x) = cos(x)", linewidth=2)
plt.xlabel('x')
plt.ylabel('y')
plt.title('sin(x) and its Derivative cos(x)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.axhline(y=0, color='k', linestyle='-', alpha=0.3)
plt.axvline(x=0, color='k', linestyle='-', alpha=0.3)
plt.show()

Example with Higher-Order Polynomial

Here's how to handle more complex functions like f(x) = x³ ? 2x² + x ?

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return x**3 - 2*x**2 + x

x = np.linspace(-1, 3, 200)
y = f(x)
dfdx = np.gradient(y, x)

plt.figure(figsize=(10, 7))
plt.subplot(2, 1, 1)
plt.plot(x, y, 'b-', linewidth=2)
plt.title('Original Function: f(x) = x³ - 2x² + x')
plt.ylabel('f(x)')
plt.grid(True, alpha=0.3)

plt.subplot(2, 1, 2)
plt.plot(x, dfdx, 'r-', linewidth=2)
plt.title("Derivative: f'(x) = 3x² - 4x + 1")
plt.xlabel('x')
plt.ylabel("f'(x)")
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Key Points

  • np.gradient(y, x) calculates numerical derivatives by approximating slopes between adjacent points
  • Higher resolution (more points) gives more accurate derivative approximations
  • The method works for any function that can be evaluated numerically
  • Always use the same spacing for x values to ensure accuracy

Comparison Table

Function Analytical Derivative NumPy Method
2x np.gradient(x**2, x)
sin(x) cos(x) np.gradient(np.sin(x), x)
e? e? np.gradient(np.exp(x), x)

Conclusion

NumPy's gradient() function provides an effective way to calculate numerical derivatives, while Matplotlib enables clear visualization of both functions and their derivatives. This approach works well for any mathematically defined function and helps visualize calculus concepts effectively.

Updated on: 2026-03-27T14:33:56+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements