Plot a Math Function in Matplotlib with NumPy linspace

Plot y = f(x) in Matplotlib by building x with np.linspace, calling the function on the whole array, and passing both to ax.plot. Covers point counts, several functions, discontinuities, piecewise functions, parametric curves, and implicit equations.

To plot a math function in Matplotlib, build the x values with np.linspace(start, stop, num), compute y = f(x) with NumPy functions so the whole array is evaluated at once, and call ax.plot(x, y). A few hundred points is enough to make the curve look smooth. The code was written for Matplotlib 3.11 and NumPy 2.5.

Quick Example

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2 * np.pi, 2 * np.pi, 400)   # 400 evenly spaced points, both ends included
y = np.exp(-np.abs(x) / 4) * np.cos(2 * x)    # a decaying wave

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x, y, color="#e76f51", linewidth=2)
ax.set_xlabel("x")
ax.set_ylabel("f(x)")
ax.set_title(r"$f(x) = e^{-|x|/4}\cos(2x)$")
plt.show()

Line chart of a decaying cosine wave that peaks at 1 in the middle and whose waves shrink toward both ends of the x axis

ax.plot doesn't know anything about functions. It draws straight lines between the (x, y) points you give it, so "plotting a function" means sampling it at many x values and letting the lines blend into a curve. The $...$ title is a LaTeX-style equation rendered by Matplotlib's built-in mathtext, so no LaTeX install is needed.

linspace vs arange: Which Should I Use?

Use np.linspace for plotting. You say how many points you want and both endpoints are included. np.arange(start, stop, step) takes a step size and stops before stop, and floating-point steps can give you one point more or fewer than you expect.

print(np.linspace(0, 1, 5))        # [0.   0.25 0.5  0.75 1.  ]
print(np.arange(0, 1, 0.25))       # [0.   0.25 0.5  0.75]   the 1 is missing
print(len(np.arange(0, 1, 0.1)))   # 10, not 11

Use arange when the step is the thing that matters, such as whole years or integer steps. For a smooth curve, linspace is the safer default.

How Many Points Does linspace Need?

Enough that the straight segments between points can't be seen. The same function, sin(3x), drawn with 8, 30, and 400 points:

fig, axes = plt.subplots(1, 3, figsize=(12, 3.4), sharey=True, layout="constrained")
for ax, n in zip(axes, (8, 30, 400)):
    x = np.linspace(0, 2 * np.pi, n)
    ax.plot(x, np.sin(3 * x), color="#264653", linewidth=2, marker="o", markersize=3)
    ax.set_title(f"num={n}")
plt.show()

Three panels of the same sine wave drawn with 8, 30, and 400 points, where the 8-point version is a jagged zigzag and the 400-point version is smooth

With 8 points the curve is a zigzag that misses the peaks. At 30 it follows the wave, but the peaks are still pointed. At 400 it is smooth, and the markers have merged into the line. Use at least 200 for a normal-sized chart, and more (1,000 to 2,000) for functions that oscillate quickly. More points are cheap: Matplotlib draws 100,000 of them in a fraction of a second.

Plot Several Functions on the Same Axes

Wrap the two steps in a small helper that takes any function, and call it once per curve. This example compares sin(x) with its first two Taylor approximations:

def plot_function(ax, f, start, stop, num=400, **kwargs):
    x = np.linspace(start, stop, num)
    ax.plot(x, f(x), **kwargs)

fig, ax = plt.subplots(figsize=(8, 4.5))
plot_function(ax, np.sin, -2 * np.pi, 2 * np.pi, color="black", linewidth=2.5, label="sin(x)")
plot_function(ax, lambda x: x, -2 * np.pi, 2 * np.pi, color="#e76f51", label="x")
plot_function(ax, lambda x: x - x**3 / 6, -2 * np.pi, 2 * np.pi, color="#2a9d8f", label="x - x³/6")
plot_function(ax, lambda x: x - x**3 / 6 + x**5 / 120, -2 * np.pi, 2 * np.pi,
              color="#e9c46a", label="x - x³/6 + x⁵/120")

ax.axhline(0, color="gray", linewidth=0.8)
ax.set_ylim(-2, 2)
ax.set_xlabel("x")
ax.legend(loc="upper right")
plt.show()

Sine curve in black with three polynomial approximations that follow it near zero and then diverge away from it

Each approximation hugs the sine curve near zero and then flies off. Setting ax.set_ylim(-2, 2) keeps those runaway polynomials from squashing the sine wave. To draw the x and y axes through the origin instead of at the edge, see centering the spines.

Why Does My Function Fail With an Array?

NumPy functions (np.sin, np.exp, np.sqrt) work on a whole array, but plain Python code often doesn't. Two errors come up all the time:

import math

def relu(x):
    if x < 0:           # fails: x is an array, so "x < 0" has many answers
        return 0
    return x

x = np.linspace(-3, 3, 7)
for bad in (lambda: relu(x), lambda: math.sin(x)):
    try:
        bad()
    except (ValueError, TypeError) as err:
        print(type(err).__name__, "-", err)
ValueError - The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
TypeError - only 0-dimensional arrays can be converted to Python scalars

The fix is to use the NumPy version of each function (np.sin instead of math.sin) and replace if with np.where(condition, value_if_true, value_if_false). If the function is too complicated for that, np.vectorize(f) calls it once per element. It works but runs at Python speed, so keep it for functions you can't rewrite.

Plot a Function With Gaps: tan(x) and 1/x

Functions with a vertical asymptote cause the most confusing charts. Matplotlib connects every point to the next, so the jump from very large positive to very large negative draws a near-vertical line that isn't part of the function. Replace the huge values with np.nan. Matplotlib leaves a gap wherever it finds one:

x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)
y_raw = np.tan(x)
y_masked = np.where(np.abs(y_raw) > 8, np.nan, y_raw)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4), sharey=True, layout="constrained")
ax1.plot(x, y_raw, color="#9d4edd")
ax1.set_title("Raw tan(x)")
ax2.plot(x, y_masked, color="#9d4edd")
ax2.set_title("Values above 8 replaced with NaN")
ax1.set_ylim(-10, 10)
plt.show()

Two panels of tan(x), the left with vertical lines joining the branches at each asymptote and the right with clean separate curves

The left panel has the stray vertical lines. The right one shows five clean branches. Pick a threshold a little beyond your y-limits so the curve still runs off the top and bottom of the axes. The same trick works for 1 / x, np.log at zero, or any function that returns inf. NumPy prints a divide-by-zero warning in those cases that you can ignore, or silence with with np.errstate(divide="ignore"):.

Plot a Piecewise Function

A function that changes formula at some point is easiest to plot as separate pieces, each drawn on its own mask. That also lets you show a jump with an open circle (the value isn't included) and a filled circle (it is):

x = np.linspace(-2, 4, 600)
left = x < 1          # first rule: x²
right = x >= 1        # second rule: 3 - x

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(x[left], x[left] ** 2, color="#e76f51", linewidth=2.5)
ax.plot(x[right], 3 - x[right], color="#264653", linewidth=2.5)
ax.plot(1, 1, "o", markerfacecolor="white", markeredgecolor="#e76f51", markersize=9)   # not included
ax.plot(1, 2, "o", color="#264653", markersize=9)                                      # included
ax.set_xlabel("x")
ax.set_ylabel("f(x)")
plt.show()

Parabola that rises to an open circle at x equals 1, then a falling straight line that starts from a filled circle higher up at x equals 1

If you don't need the open and closed markers, y = np.where(x < 1, x**2, 3 - x) gives the same curve in one line, with a short slanted segment across the jump.

Plot a Parametric Curve

For curves where x and y both depend on a third variable t, such as circles, spirals, and Lissajous figures, make t with linspace and compute both coordinates from it. Call ax.set_aspect("equal") so a circle looks like a circle:

t = np.linspace(0, 2 * np.pi, 1000)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4.4), layout="constrained")

ax1.plot(np.sin(3 * t), np.sin(2 * t), color="#2a9d8f", linewidth=2)
ax1.set_title("Lissajous: x = sin(3t), y = sin(2t)")
ax1.set_aspect("equal")

r = np.cos(4 * t)
ax2.plot(r * np.cos(t), r * np.sin(t), color="#e76f51", linewidth=2)
ax2.set_title("Rose: r = cos(4θ)")
ax2.set_aspect("equal")
plt.show()

Two curves side by side: a looping Lissajous figure and an eight-petal rose

For polar curves like the rose you can also use polar axes with projection="polar", but converting r and θ to x and y works on any axes. See aspect ratio and equal axes for more on set_aspect.

Plot an Implicit Equation Like x² + y² = 1

Some curves can't be solved for y. Evaluate the equation on a grid with np.meshgrid and draw the contour where the expression equals zero:

x = np.linspace(-1.6, 1.6, 800)
y = np.linspace(-1.6, 1.6, 800)
X, Y = np.meshgrid(x, y)
F = (X**2 + Y**2 - 1) ** 3 - X**2 * Y**3     # the heart curve; F = 0 on the curve

fig, ax = plt.subplots(figsize=(5, 5))
ax.contour(X, Y, F, levels=[0], colors="#d62828", linewidths=2.5)
ax.set_aspect("equal")
ax.set_title(r"$(x^2 + y^2 - 1)^3 = x^2 y^3$")
plt.show()

A red heart-shaped curve drawn from an implicit equation

levels=[0] tells contour to draw only the line where F is zero. Rearrange any equation into left - right and the same code works. See contour plots for filled contours and more options.

Which Approach Should I Use?

Your function Use
y = f(x) that is smooth x = np.linspace(a, b, 400), then ax.plot(x, f(x))
Has asymptotes (tan, 1/x) Replace large values with np.nan before plotting
Changes formula by range Plot each piece on its own mask, or use np.where
x and y both depend on t t = np.linspace(...), then ax.plot(x(t), y(t))
Can't be solved for y np.meshgrid and ax.contour(X, Y, F, levels=[0])
Uses math.sin or if x < 0 Switch to np.sin and np.where, or wrap with np.vectorize

Practical Tips

  • Evaluate with NumPy, not math. np.sin, np.exp, and np.sqrt accept arrays. The math versions only accept single numbers.
  • Use more points near fast changes. sin(50x) on 200 points looks like noise. Raise num until the curve stops changing.
  • Set y-limits for functions that blow up. ax.set_ylim(-10, 10) keeps a runaway curve from flattening everything else.
  • Label curves directly. label="..." plus ax.legend() is the quickest way to tell several functions apart. See legends.
  • Use a log scale for exponentials. Curves like 2**x become straight lines on a logarithmic axis.

Similar Topics