← Data analysis with Python

Scatter plots for relationships

Plot two numbers per row to see whether they move together.

Start this lesson

A scatter plot puts one dot per row, using one column for x and another for y. It answers "is there a relationship?": do students who study more hours score higher? Do hotter days sell more ice cream? If the dots drift upward from left to right, the two values tend to rise together (a positive relationship). Drifting downward means one tends to fall as the other rises. A shapeless cloud suggests little relationship. ax.scatter(x, y) draws it.

import io
import pandas as pd

csv_text = """name,group,math,reading,hours
Amara,A,88,92,6
Ben,A,72,80,3
Chen,B,95,85,8
Dalia,B,64,70,2
Emeka,A,79,88,5
Fatima,B,91,94,7
Gus,A,58,65,1
Hana,B,83,77,5
"""
scores = pd.read_csv(io.StringIO(csv_text))
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.scatter(scores["hours"], scores["math"])
ax.set_title("Study hours and math score")
ax.set_xlabel("Hours studied per week")
ax.set_ylabel("Math score")

Each dot is one student. The dots rise from left to right: in this group, students who studied more tended to score higher.

Put the variable you think might influence the other on the x-axis. That is only a convention; the chart itself cannot prove that one causes the other (more on that soon).