Lesson 6 of 12 · Functions and Graphs
Plotting Functions
Learn the coordinate plane, x and y axes, points and how to draw the graph of a function from a table of values. With interactive graphs and Python examples.
- 6 min read
- Beginner
- Reviewed
- The coordinate plane: axes, origin and points
- How to read and write coordinates
- How to plot a function from a table of values
- How to read useful facts straight off a graph
A picture is worth a thousand numbers
A list of numbers is hard to understand. A graph shows the whole pattern at a glance: where values rise, where they fall and where they cross zero. Data scientists draw graphs all day.
The coordinate plane
A simple way to remember the order: along the corridor, then up the stairs.
The graph of a function
To draw one by hand, make a table of values: pick some inputs, work out the outputs, and plot each pair.
def f(x):
return x ** 2 - 2
print(" x | f(x)")
print("---+-----")
for x in range(-3, 4):
print(f"{x:2} | {f(x):3}")Join the points smoothly, and you get the curve below. A computer simply does the same thing with hundreds of points.
Reading a graph
A graph answers questions without any calculation:
The minimum is especially important in AI. Training a model means finding the parameter values where the error is at its minimum, the bottom of a curve like this one.
Try changing the curve
Move the sliders to change the numbers in y = ax² + bx + c and watch the curve respond:
What happens when a is negative? When c changes? Building this kind of intuition is exactly what graphs are for.
Graphs in Python
In real projects you draw graphs with the matplotlib library. On your own computer, this short program draws the curve above in a window:
import matplotlib.pyplot as plt
xs = []
ys = []
for i in range(-40, 41):
x = i / 10
xs.append(x)
ys.append(x ** 2 - 2)
plt.plot(xs, ys)
plt.axhline(0, color="grey")
plt.axvline(0, color="grey")
plt.title("f(x) = x² - 2")
plt.show()You will use matplotlib throughout the data courses.
Common mistakes
Build a table of points for a line, ready to plot.
# Make a table of values for y = 2x - 1, for x from -2 to 2. # Print each point as a pair of coordinates, then say where the line crosses the y-axis. # Output must be exactly: # (-2, -5) # (-1, -3) # (0, -1) # (1, 1) # (2, 3) # The y-intercept is -1
Where is the point (-3, 4)?
Summary
- The coordinate plane has a horizontal x-axis, a vertical y-axis and the origin at (0, 0).
- Coordinates
(x, y)mean across first, then up. - The graph of a function plots every point
(x, f(x)). A table of values gets you started. - Graphs show intercepts, the minimum and the overall shape at a glance.
Next: straight-line graphs, the simplest and most useful functions of all.
Finished reading? Tick it off to track your progress.