The fastest way to understand a function is to see it. What does y = x³ − 3x look like? Where does it cross zero? Where does it turn? A plot answers all three in a second, where algebra might take ten minutes. That's why every lesson in this course shows graphs, and why you should get into the habit of plotting every new function you meet.
Python makes this easy. This lesson shows the complete recipe, one step at a time: create inputs with NumPy, calculate outputs, and draw them with matplotlib. You'll learn why curves sometimes look jagged, how to put several functions on one chart, how to draw the axes through zero like a textbook graph, and how to handle functions with gaps, like 1/x.
What you need first: what is a function? and Python as a calculator for maths. Basic plotting is covered in the Python charts course, but you don't need it for this lesson.
Key terms
- NumPy array: a list of numbers that you can do maths on all at once.
- np.linspace(a, b, n): n evenly spaced numbers from a to b.
- Vectorised: applying a calculation to a whole array at once, without a loop.
- Resolution: how many points you calculate; more points give a smoother curve.
- Asymptote: a line a curve gets closer and closer to but never reaches.
The recipe
Every function plot follows the same three steps:
- Inputs: make lots of x values with
np.linspace. - Outputs: calculate y = f(x) for all of them at once.
- Draw:
plt.plot(x, y), then label it.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3, 3, 200) # 1. 200 inputs from -3 to 3
y = x ** 3 - 3 * x # 2. outputs, all at once
fig, ax = plt.subplots()
ax.plot(x, y) # 3. draw
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("y = x³ − 3x")
ax.grid(alpha=0.3)
plt.show()
In one glance you can see the curve turns at x = −1 and x = 1, and crosses zero three times.
Step 1: np.linspace
print(np.linspace(0, 1, 5))
print(np.linspace(-2, 2, 9))
[0. 0.25 0.5 0.75 1. ]
[-2. -1.5 -1. -0.5 0. 0.5 1. 1.5 2. ]
np.linspace(start, stop, how_many) includes both ends and spaces the numbers evenly.
Step 2: vectorised maths
With a NumPy array, x ** 3 - 3 * x calculates the answer for every element in one go. No loop needed:
x_small = np.array([-2, -1, 0, 1, 2])
print(x_small ** 3 - 3 * x_small)
[-2 2 0 -2 2]
For functions like square roots, sines and logarithms, use NumPy's versions (np.sqrt, np.sin, np.log, np.exp), not the math module's, because only NumPy's work on whole arrays.
Why curves look jagged: resolution
matplotlib draws straight lines between your points. With too few points, a curve looks like a set of straight segments:
fig, ax = plt.subplots()
for n, style in [(5, "o-"), (200, "-")]:
xs = np.linspace(-3, 3, n)
ax.plot(xs, xs ** 2, style, label=f"{n} points")
ax.set_title("y = x²: more points, smoother curve")
ax.legend()
plt.show()
With 5 points, the parabola looks pointy and wrong. A few hundred points is plenty for almost any function.
Several functions on one chart
Call plot once per function, give each a label, and add a legend. Drawing the axes through the origin makes it look like a textbook graph:
x = np.linspace(-2, 2, 200)
fig, ax = plt.subplots()
ax.plot(x, x, label="y = x")
ax.plot(x, x ** 2, label="y = x²")
ax.plot(x, x ** 3, label="y = x³")
ax.spines["left"].set_position("zero")
ax.spines["bottom"].set_position("zero")
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.set_ylim(-4, 4)
ax.set_title("Powers of x", pad=15)
ax.legend()
plt.show()
The chart shows something worth knowing: between −1 and 1, higher powers are closer to zero (x³ is flattest), and beyond that, they grow faster.
Functions with gaps: 1/x
y = 1/x has no value at x = 0. Plotting it naively draws a false vertical line joining the two halves, because matplotlib connects neighbouring points. The fix: split the inputs into two separate ranges:
fig, ax = plt.subplots()
for xs in [np.linspace(-4, -0.2, 100), np.linspace(0.2, 4, 100)]:
ax.plot(xs, 1 / xs, color="tab:blue")
ax.axhline(0, color="grey", lw=0.8)
ax.axvline(0, color="grey", lw=0.8, ls="--")
ax.set_ylim(-5, 5)
ax.set_title("y = 1/x has a gap at x = 0")
plt.show()
The curve gets closer and closer to both axes without touching them. Lines like these are called asymptotes. set_ylim stops the huge values near zero from squashing the rest of the chart.
Plot your own functions
Wrap the recipe in a helper, and plotting any function is one line:
def plot_function(f, start=-5, stop=5, title=""):
xs = np.linspace(start, stop, 300)
fig, ax = plt.subplots()
ax.plot(xs, f(xs))
ax.axhline(0, color="grey", lw=0.8)
ax.axvline(0, color="grey", lw=0.8)
ax.set_title(title)
ax.grid(alpha=0.3)
plt.show()
plot_function(lambda x: 1 / (1 + np.exp(-x)), -8, 8, "The sigmoid: 1 / (1 + e⁻ˣ)")
lambda x: ... is a short way to write a one-line function. This one is the sigmoid, which squeezes any number into the range 0 to 1. It's how logistic regression turns a score into a probability; you'll meet it again in sigmoid and softmax functions explained.
Practice
- What does
np.linspace(0, 10, 6)produce?
Show the answer
[ 0. 2. 4. 6. 8. 10.]: six evenly spaced numbers including both ends.
- Plot y = x² − 4 from −4 to 4. Where does it cross the x-axis?
Show the answer
x = np.linspace(-4, 4, 200), plt.plot(x, x ** 2 - 4). It crosses at x = −2 and x = 2.
- Why does
math.sqrt(x)fail when x is a NumPy array, and what should you use?
Show the answer
math.sqrt only handles single numbers. Use np.sqrt(x), which works element by element on arrays.
- Plot y = 2x + 1 and y = −x + 4 on the same chart. Where do they cross?
Show the answer
Solve 2x + 1 = −x + 4: x = 1, y = 3. The lines cross at (1, 3).
- Your plot of y = 1/(x − 1) shows a strange vertical line at x = 1. Why, and how do you fix it?
Show the answer
matplotlib joins the last point left of 1 to the first point right of 1. Plot the two sides separately, for example np.linspace(-3, 0.9, 100) and np.linspace(1.1, 4, 100).
Key takeaways
- The recipe:
x = np.linspace(...),y = f(x),plt.plot(x, y). - NumPy calculates every output at once; use
np.sqrt,np.expand friends, notmath. - Use a few hundred points for smooth curves.
- Plot several functions with labels and a legend to compare them.
- Split the inputs around gaps like x = 0 in 1/x, and set
ylimto keep the chart readable.
Frequently asked questions
How do I plot a mathematical function in Python?
Create input values with np.linspace, calculate outputs with a NumPy expression, then call plt.plot(x, y) from matplotlib and add labels.
Why does my curve look jagged in matplotlib?
matplotlib connects your points with straight lines. If you calculate too few points, the segments are visible. Increase the number of points in np.linspace to a few hundred.
What is np.linspace?
A NumPy function that returns a chosen number of evenly spaced values between a start and an end, including both. It's the standard way to create x values for plotting.
What to learn next
- Meet the shapes you'll see again and again in common function shapes.
- Revisit slope and intercept.