How to calculate and plot the derivative of a function using matplotlib and python ?
Last Updated :
28 Mar, 2023
In this article we will plot the derivative of a function using matplotlib and python.
Modules used-
Matplotlib: Matplotlib is one of the most popular Python packages used for data visualization. It is a cross-platform library for making 2D plots from data in arrays.
NumPy: It is a python library that is use to for working with arrays, it also supports large multi-dimensional arrays and matrices, it also has several mathematical functions.
SciPy: Python has a library named as SciPy that is used for mathematical, scientific and engineering calculations. This library depends on NumPy, and provides various numerical operations.
Approach:
- Import the modules
- Define methods for function and its derivative
- Use numpy linspace function to make x-axis spacing.
- Plot the function and its derivative
- Change the limits of axis using gca() function
- Plot the text using text() function
Explanation: The scipy.misc library has a derivative() function which accepts one argument as a function and other is the variable w.r.t which we will differentiate the function. So we will make a method which will return the function and second method which will return the the derivative of that function.
After this, we will use the numpy linspace() function which set the range of the x-axis. The plot() function will be used to plot the function and also the derivative of that function.
Example 1: In this example we will plot the derivative of:- f(x)=2x3+x+3
[tabby title="Python3"][sourcecode language="python3"]# importing the library
import matplotlib.pyplot as plt
from scipy.misc import derivative
import numpy as np
# defining the function
def function(x):
return 2*x*x*x+x+3
# calculating its derivative
def deriv(x):
return derivative(function, x)
# defininf x-axis intervals
y = np.linspace(-6, 6)
# plotting the function
plt.plot(y, function(y), color='purple', label='Function')
# plotting its derivative
plt.plot(y, deriv(y), color='green', label='Derivative')
# formatting
plt.legend(loc='upper left')
plt.grid(True)
[/sourcecode][tabbyending]
Output:
Example 2: In this example we will plot the derivative of:- f(x)=x4+x2+5
[tabby title="Python3"][sourcecode language="python3"]# importing the library
import matplotlib.pyplot as plt
from scipy.misc import derivative
import numpy as np
# defining the function
def function(x):
return x*x*x*x+x*x+5
# calculating its derivative
def deriv(x):
return derivative(function, x)
# defininf x-axis intervals
y = np.linspace(-15, 15)
# plotting the function
plt.plot(y, function(y), color='red', label='Function')
# plotting its derivative
plt.plot(y, deriv(y), color='green', label='Derivative')
# formatting
plt.legend(loc='upper left')
plt.grid(True)
[/sourcecode][tabbyending]
Output:
Example 3: In this example we will plot the derivative of:- f(x)=4x2+x+1. Also, we will use some formatting using the gca() function that will change limits of the axis so that both x,y axes intersect at origin. The text() function which comes under matplotlib library plots the text on the graph and takes argument as (x,y) coordinates. We will also do some formatting.
[tabby title="Python3"][sourcecode language="python3"]# importing modules
import matplotlib.pyplot as plt
from scipy.misc import derivative
import numpy as np
# method to return function
def function(x):
return 4*x**2+x+1
# method to return its derivative
def deriv(x):
return derivative(function, x)
#range in x-axis
y = np.linspace(-6, 6)
# plotting function
plt.plot(y, function(y), color='brown', label='Function')
# plotting its derivative
plt.plot(y, deriv(y), color='blue', label='Derivative')
# changing limits of y-axis
plt.gca().spines['left'].set_position('zero',)
# changing limits of x-axis
plt.gca().spines['bottom'].set_position('zero',)
plt.legend(loc='upper left')
# plotting text in the graph
plt.text(5.0, 1.0, r"$f'(x)=8x+1$", horizontalalignment='center',
fontsize=18, color='blue')
plt.text(-4.4, 25.0, r'$f(x)=4x^2+x+1$', horizontalalignment='center',
fontsize=18, color='brown')
plt.grid(True)
[/sourcecode][tabbyending]
Output: