DS Plotting Functions
A formula tells you how to compute a value; a plot shows you the shape of the whole relationship at a glance. In this lesson you'll draw functions and data with Matplotlib, the plotting library that pandas and seaborn are built on.
Drawing a function
To plot f(x), compute it for many x-values and connect the points:
- Create the inputs with
np.linspace(start, stop, n). - Compute the outputs with a vectorised formula.
- Call
plt.plot(x, y), label the axes, andplt.show().
import numpy as np
import matplotlib.pyplot as plt
minutes = np.linspace(0, 60, 61)
price = 0.20 * minutes + 1.50
plt.plot(minutes, price, color="#ff6f00")
plt.xlabel("Ride length (minutes)")
plt.ylabel("Price (EUR)")
plt.title("Riverside Bikes pay-per-minute price")
plt.grid(True, alpha=0.3)
plt.show()
print(f"Price at 0 min: {price[0]:.2f}, at 60 min: {price[-1]:.2f}")Price at 0 min: 1.50, at 60 min: 13.50
The result is a straight line that starts at €1.50 on the y-axis (the intercept) and climbs €0.20 for every minute (the slope).
Note: In these playgrounds
plt.show()doesn't open a window; the figure is drawn under the output when the program finishes.
Comparing several functions
Plotting several functions on the same axes makes comparisons easy. Which plan is cheapest for which ride length?
import numpy as np
import matplotlib.pyplot as plt
m = np.linspace(0, 60, 61)
per_minute = 0.20 * m + 1.50
member = 0.10 * m + 4.00
day_pass = np.full_like(m, 9.00)
plt.plot(m, per_minute, label="Pay per minute")
plt.plot(m, member, label="Member")
plt.plot(m, day_pass, label="Day pass", linestyle="--")
plt.xlabel("Ride length (minutes)")
plt.ylabel("Price (EUR)")
plt.legend()
plt.show()
cheapest = np.array(["per minute", "member", "day pass"])[
np.argmin(np.vstack([per_minute, member, day_pass]), axis=0)]
for minutes in [10, 25, 40, 55]:
print(f"{minutes} min: cheapest plan is {cheapest[minutes]}")10 min: cheapest plan is per minute
25 min: cheapest plan is per minute
40 min: cheapest plan is member
55 min: cheapest plan is day pass
Where two lines cross, the plans cost the same (at exactly 25 minutes the code reports the first of the tied plans). Pay-per-minute and member cross at 25 minutes (0.20·25 + 1.50 = 0.10·25 + 4.00 = 6.50); the member line meets the day pass at 50 minutes.
Plotting data: scatter versus line
Measured data is usually drawn with markers (a scatter plot) rather than a line, because there is no guarantee about the values between observations. Overlaying a function on the data shows how well it describes them:
import numpy as np
import matplotlib.pyplot as plt
temp = np.array([24.1, 15.4, 26.3, 22.1, 6.4, 29.4, 23.8, 24.4, 7.3, 15.7])
rides = np.array([414, 298, 439, 405, 254, 523, 497, 428, 209, 368])
x = np.linspace(5, 30, 50)
guess = 150 + 12 * x # the manager's rule of thumb
plt.scatter(temp, rides, label="Observed days")
plt.plot(x, guess, color="red", label="Guess: 150 + 12 x temp")
plt.xlabel("Temperature (°C)")
plt.ylabel("Rides")
plt.legend()
plt.show()
errors = rides - (150 + 12 * temp)
print("Errors of the guess:", errors.round(1))
print("Mean error:", errors.mean().round(1))Errors of the guess: [-25.2 -36.8 -26.6 -10.2 27.2 20.2 61.4 -14.8 -28.6 29.6]
Mean error: -0.4
The guess is right on average (mean error −0.4 rides), but single days miss by up to 61 rides: the points scatter on both sides of the line. In the next lesson you'll compute the best slope and intercept instead of guessing.
Plotting straight from pandas
DataFrames have a .plot() method that calls Matplotlib for you. kind selects the chart type:
import pandas as pd
import matplotlib.pyplot as plt
days = pd.DataFrame({
"day": range(1, 11),
"rides": [414, 298, 439, 405, 254, 523, 497, 428, 209, 368],
})
ax = days.plot(x="day", y="rides", kind="line", marker="o", legend=False)
ax.set_ylabel("Rides")
ax.set_title("Daily rides, first 10 days")
plt.show()
print("Line chart of", len(days), "days")Line chart of 10 days
kind= |
Chart |
|---|---|
"line" |
Line chart (default) |
"scatter" |
Scatter plot (needs x and y) |
"bar" / "barh" |
Bar chart |
"hist" |
Histogram |
"box" |
Box plot |
Tip: Always label axes with units. A chart without units forces the reader to guess.
Test yourself
What does np.linspace(0, 60, 61) create?
- 60 random numbers
- 61 evenly spaced values from 0 to 60
- The numbers 0 to 61
- A 60 × 61 grid
Why are measured data usually drawn as a scatter plot instead of a connected line?
- Lines are slower to draw
- There is no measurement between the observations, so connecting them implies values that weren't observed
- Scatter plots use less colour
- Matplotlib can't draw lines for data
Where two plotted price lines cross, the two plans…
- have the same slope
- cost the same for that ride length
- have the same intercept
- are both free