Graphing with Computers
A plotting library draws a graph by evaluating the function at finitely many points and joining them with straight segments. That is usually fine and sometimes badly misleading. This lesson covers viewing windows, sampling and aliasing, fake lines across asymptotes, and families of functions, so you can trust what the screen shows you, or know when not to.
Plotting itself is covered in Matplotlib Plotting; here we are concerned with the mathematics of what a plot can and cannot show.
How a plot is made
plt.plot(x, f(x)) with x = np.linspace(a, b, n) does three things: it samples at equally spaced points, connects consecutive samples with line segments, and maps the viewing rectangle onto the screen. Each step can hide the truth:
| Problem | Cause | Remedy |
|---|---|---|
| a feature is invisible | window too large or too small | try several windows, zoom on interesting points |
| a wave looks slower than it is | too few samples (aliasing) | more samples than twice the frequency, ideally far more |
| a vertical line at an asymptote | segments join and samples | mask large values, or split the domain |
| two functions look identical | only the dominant term is visible at large scale | compare on a smaller window or plot the difference |
| a graph misses part of its domain | odd roots computed as complex numbers | use np.cbrt or sign-aware formulas |
Sampling and aliasing
If a function oscillates faster than the sampling rate can resolve, the samples line up with a different, slower wave. This is aliasing, and it is the same effect that makes wagon wheels spin backwards in films.
import numpy as np
t = np.arange(10) / 10 # 10 samples per second over 1 s
fast = np.sin(2 * np.pi * 11 * t) # an 11 Hz wave
slow = np.sin(2 * np.pi * 1 * t) # a 1 Hz wave
print(np.round(fast, 4))
print(np.round(slow, 4))
print("identical samples:", bool(np.allclose(fast, slow)))[ 0. 0.5878 0.9511 0.9511 0.5878 0. -0.5878 -0.9511 -0.9511
-0.5878]
[ 0. 0.5878 0.9511 0.9511 0.5878 0. -0.5878 -0.9511 -0.9511
-0.5878]
identical samples: True
At 10 samples per second, an 11 Hz signal is indistinguishable from a 1 Hz one, because . The Nyquist–Shannon sampling theorem says you need more than two samples per period to recover a sine wave; for a graph that also looks smooth, use dozens.
Asymptotes and fake vertical lines
Plotting on joins a huge positive sample just left of to a huge negative sample just right of it, drawing a vertical line that is not part of the graph. The fix is to break the line where the values are too large, by replacing them with NaN (Matplotlib leaves gaps at NaN):
import numpy as np
x = np.linspace(0, 2 * np.pi, 1000)
y = np.tan(x)
jumps = int(np.sum((np.abs(np.diff(y)) > 50) & (y[:-1] * y[1:] < 0)))
y_masked = np.where(np.abs(y) > 10, np.nan, y)
print("huge jumps that flip sign:", jumps)
print("points hidden:", int(np.isnan(y_masked).sum()), "of", y.size)huge jumps that flip sign: 2
points hidden: 64 of 1000
The two sign-flipping jumps are the asymptotes at and (other neighbours near an asymptote also differ by a lot, but stay on the same side). A window of then shows the correct picture.
Windows: local and global behaviour
No single window shows everything. Large windows show end behaviour, dominated by the leading term; small windows show roots, turning points and inflection points. On , and look the same, since , yet near the origin has a root at 4 and a minimum at that lacks. A reliable workflow is to compute the interesting points first (where , and later where and ) and then choose a window that contains them.
Families of functions
Plotting a function for several values of a parameter shows how the parameter changes the shape. In the family , the turning points appear only for negative :
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-2.5, 2.5, 500)
plt.figure(figsize=(6, 4))
for c in [-3, -1, 0, 1, 3]:
plt.plot(x, x**3 + c * x, label=f"c = {c}")
plt.ylim(-6, 6)
plt.axhline(0, color="grey", lw=0.5)
plt.legend()
plt.title("The family x³ + cx")
for c in [-3, -1, 0, 1, 3]:
y = x**3 + c * x
turns = int(np.sum(np.diff(np.sign(np.diff(y))) != 0))
print(f"c = {c:>2}: turning points = {turns}")c = -3: turning points = 2
c = -1: turning points = 2
c = 0: turning points = 0
c = 1: turning points = 0
c = 3: turning points = 0
For the turning points sit at ; as rises to 0 they merge and disappear. Chapter 4 proves this with the derivative .
Graphs as a tool for solving equations
Counting where two graphs cross is a quick way to count the solutions of an equation, and sign changes in the sampled difference give starting brackets for an exact root finder. A plot finds candidates; a proof or a careful numeric method confirms them. Missing a root that sits between two samples (a "double touch" where has no sign change) is a classic failure.
In software
Everyone who draws data meets these issues: dashboards that downsample a time series can hide spikes (an aliasing effect), audio code must low-pass filter before resampling, games that sample collisions once per frame can let a fast object pass through a wall ("tunnelling"), and log-scaled axes (Ticks and Scales) are the standard way to show quantities that span orders of magnitude.
Exercises
Exercise 1: Predict the alias
A 9 Hz sine wave is sampled 10 times per second. Which frequency do the samples appear to have, and with which sign?
Answer
It looks like a 1 Hz wave with the opposite sign: .
Solution
The apparent frequency is , and the wave is mirrored (like a wheel turning backwards).
Exercise 2: Choose a window
Find a viewing rectangle that shows all roots and both turning points of .
Answer
For example , . Roots at 0, 10, 20; turning points near () and ().
Solution
, so the roots are 0, 10 and 20. The turning points solve (from chapter 3's derivative, or read off a rough plot):
The graph is symmetric about the middle root , which is why the two values are opposites.
Exercise 3: Count solutions with a sampled graph
How many solutions does have? Use sign changes of on a fine grid. Explain why it is enough to search .
Answer
7 solutions, near −9.68, −8.97, −4.27, −1.75, 1.43, 5.27 and 7.07.
Solution
, so a solution needs , that is .
import numpy as np
x = np.linspace(-10, 10, 200001)
s = np.sign(np.cos(x) - x / 10)
idx = np.where(s[:-1] * s[1:] < 0)[0]
print(len(idx), [round(float(x[i]), 2) for i in idx])7 [-9.68, -8.97, -4.27, -1.75, 1.43, 5.27, 7.07]
A grid this fine could still miss a tangential touch, but none occurs here: near each crossing the two graphs meet at a clear angle.
Exercise 4: Where does the family turn?
For which values of does have two turning points? Check by finding them.
Answer
For . For they are at .
Solution
As the plot suggests, turning points exist only when the cubic dips: they are at , which is real and nonzero only for . For : , with and .
Test yourself
Why can plotting produce vertical lines at ?
- is discontinuous everywhere
- The plotter joins a large positive sample to a large negative one across the asymptote
- Matplotlib cannot compute tan
- The window is too small
Sampled 10 times per second, an 11 Hz sine looks like which wave?
- 1 Hz
- 11 Hz
- 21 Hz
- a constant
On a huge window and look the same. Why?
- They are equal
- Their ratio tends to 1 because the leading term dominates
- Plotting errors
- Both are even