Introduction
In Python, computing and visualizing derivatives is straightforward using libraries such as NumPy and Matplotlib. Whether you are working with analytical functions or discrete data, these tools allow you to approximate derivatives and display them clearly.
In this article, we focus on practical methods to compute derivatives numerically and plot both the function and its derivative, including the visualization of a tangent at a given point.
What Is a Derivative?
The derivative of a function represents the slope of the tangent line at a given point.
Numerically, we often approximate it using finite differences:
\begin{equation}
f'(x) \approx \frac{f(x + h) - f(x - h)}{2h}
\end{equation}
This is called the central difference method, and it is the foundation of most numerical derivative computations in Python.
In practice, this means we estimate the slope by looking at how the function changes slightly before and after a point.
Python Tools for Numerical Derivatives
| Method | Arrays | Single Value | Status | Speed |
|---|---|---|---|---|
numpy.gradient |
✅ | ❌ | ⭐ Recommended | Fast |
findiff |
✅ | ❌ | Active | Medium |
| Manual difference | ❌ | ✅ | Always valid | Fast |
scipy.misc |
✅ | ✅ | ❌ Deprecated | Slow |
Recommendation: Use numpy.gradient for most cases.
Method 1 — Using NumPy (Recommended)
NumPy is the standard library for numerical computing in Python and is often the best choice for computing derivatives. It is built-in and fast, requires no extra dependency, and is ideal for large datasets. The function numpy.gradient estimates derivatives using finite differences, providing a simple and efficient solution for most applications.
Compute and Plot a Derivative Using Numpy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import numpy as np import matplotlib.pyplot as plt # Function def fonction(x): return np.sin(x) + 0.3*x # Data x = np.linspace(-4, 4, 200) y = fonction(x) # Derivative (numerical) dy_dx = np.gradient(y, x) # ---- Point of interest ---- x0 = 1.5 # Closest index idx = np.argmin(np.abs(x - x0)) y0 = y[idx] slope = dy_dx[idx] # ---- Create a SHORT tangent segment ---- dx_local = 0.5 # controls length of tangent segment x_tan = np.linspace(x0 - dx_local, x0 + dx_local, 20) y_tan = y0 + slope * (x_tan - x0) # ---- Plot ---- ax = plt.subplot(111) plt.plot(x, y, label=r'$f(x)=\sin(x)+0.3x$', color='black') # Short tangent ONLY plt.plot(x_tan, y_tan, color='blue', linewidth=2, label='Tangent (local)') # Highlight point plt.scatter(x0, y0, color='red', zorder=3) # Style (your preferred style) plt.grid(True) ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('zero') ax.spines['top'].set_color('none') plt.axhline(0, color='black', linewidth=0.1) plt.axvline(0, color='black', linewidth=0.1) plt.legend() plt.title("Local Tangent Line at a Point") plt.show() |

Derivative at a Single Point
When you only need the derivative at one value, you can use the finite difference formula directly:
1 2 3 4 5 6 7 8 9 | def f(x): return x**2 x0 = 2.0 h = 1e-6 dy_dx = (f(x0 + h) - f(x0 - h)) / (2*h) print(dy_dx) |
Result:
1 | ≈ 4.0 |
Choosing the Step Size h
The choice of h is critical for numerical derivatives. If h is too large, the approximation becomes inaccurate, while if it is too small, numerical precision errors can dominate. In practice, values of h between $10^{−5}$ and $10^{−7}$ generally provide a good balance between accuracy and stability.
Plot Tangent Line at One Point
At a given point $x_0$, the derivative gives the slope of the tangent line.
The tangent line equation is:
\begin{equation}
y=f(x_0) + f'(x_0)(x-x_0)
\end{equation}
Let’s use:
\begin{equation}
f(x)=sin(x)+0.3x
\end{equation}
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import numpy as np import matplotlib.pyplot as plt # Function def fonction(x): return np.sin(x) + 0.3*x # Data x = np.linspace(-4, 4, 200) y = fonction(x) # Derivative (numerical) dy_dx = np.gradient(y, x) # ---- Point of interest ---- x0 = 1.5 # Closest index idx = np.argmin(np.abs(x - x0)) y0 = y[idx] slope = dy_dx[idx] # ---- Create a SHORT tangent segment ---- dx_local = 0.5 # controls length of tangent segment x_tan = np.linspace(x0 - dx_local, x0 + dx_local, 20) y_tan = y0 + slope * (x_tan - x0) # ---- Plot ---- ax = plt.subplot(111) plt.plot(x, y, label=r'$f(x)=\sin(x)+0.3x$', color='black') # Short tangent ONLY plt.plot(x_tan, y_tan, color='blue', linewidth=2, label='Tangent (local)') # Highlight point plt.scatter(x0, y0, color='red', zorder=3) # Style (your preferred style) plt.grid(True) ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('zero') ax.spines['top'].set_color('none') plt.axhline(0, color='black', linewidth=0.1) plt.axvline(0, color='black', linewidth=0.1) plt.legend() plt.title("Local Tangent Line at a Point") plt.show() |

Method 2 — Using findiff
findiff is a more flexible library for computing numerical derivatives, especially when you need higher-order derivatives or want more control over the numerical scheme. It is well suited for irregular grids and scientific applications where precision and customization are important. In the following example, we use the function
\begin{equation}
f(x)=x^3 - x
\end{equation}
, to illustrate how findiff approximates derivatives using finite difference operators. Its derivative is:
\begin{equation}
f'(x)=3x^2 - 1
\end{equation}
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | import numpy as np import matplotlib.pyplot as plt from findiff import FinDiff # Define the function f(x) = x^3 - x def fonction(x): return x**3 - x # Generate x values x = np.linspace(-2, 2, 100) # Compute function values y = fonction(x) # Grid spacing dx = x[1] - x[0] # Derivative operator deriv = FinDiff(0, dx, 1) # Compute derivative dy_dx = deriv(y) # Plot ax = plt.subplot(111) plt.plot(x, y, label=r'$f(x)=x^3 - x$', color='black', linestyle='dashed') plt.plot(x, dy_dx, label=r"$f'(x)=3x^2 - 1$", color='coral', linestyle='dashed') # Style plt.grid(True) ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('zero') ax.spines['top'].set_color('none') plt.axhline(0, color='black', linewidth=0.1) plt.axvline(0, color='black', linewidth=0.1) plt.legend() plt.title("Function and Its Derivative") plt.show() |

References
| Resource | Link |
|---|---|
| NumPy Gradient | https://numpy.org/doc/stable/reference/generated/numpy.gradient.html |
| findiff | https://findiff.readthedocs.io |
| Matplotlib | https://matplotlib.org |
