Lesson 17 · Data visualisation in python
Understanding Relationship Plots in Seaborn: Scatter, Regression, and Pairplot Explained
In this lesson, we will explore how to visualize relationships between data using scatter plots, regression plots, and pairplots. We will use real datasets…
- CourseData visualisation in python
- Lesson17 of 34
- Video14 min
- FormatJupyter notebook · 17 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbWelcome: Relationship Plots in Python!#
In this lesson, we will explore how to visualize relationships between data using scatter plots, regression plots, and pairplots.
We will use real datasets like airline passengers to understand trends over time.
By the end, you will be able to create beautiful visualizations and gain valuable insights from your own data.
What are Relationship Plots?#
Relationship plots show how two or more variables relate.
They help us spot patterns, trends, and outliers in data.
Common types include scatter plots, regression lines, and pair plots.
# Suppress warnings for a clean experience
import warnings; warnings.filterwarnings("ignore")
# Import useful packages
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Data setup: Load the Airline Passengers dataset
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
data = pd.read_csv(url)
print('Shape:', data.shape)
data.head()
# First visualization: see the trend over time
plt.figure(figsize=(10,5))
plt.plot(data['Month'], data['Passengers'], marker='o')
plt.title("Monthly Airline Passengers Over Time")
plt.xlabel("Month")
plt.ylabel("Number of Passengers")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Scatter Plots: Finding Patterns#
Scatter plots let us look for patterns or relationships between two variables.
Each point shows one set of values from our data.
# Prepare data for scatter: extract year and month number
data['Year'] = data['Month'].str[:4].astype(int)
data['Month_num'] = data['Month'].str[5:].astype(int)
# Simple scatter plot: Passengers vs Year
plt.figure(figsize=(8,5))
plt.scatter(data['Year'], data['Passengers'])
plt.title("Passengers vs Year")
plt.xlabel("Year")
plt.ylabel("Number of Passengers")
plt.show()
# Scatter plot with color: Passengers by Month
plt.figure(figsize=(8,5))
sns.scatterplot(x='Month_num', y='Passengers', hue='Year', data=data, palette='viridis')
plt.title("Monthly Passengers Colored by Year")
plt.xlabel("Month Number")
plt.ylabel("Number of Passengers")
plt.legend(title="Year", bbox_to_anchor=(1.05,1), loc='upper left')
plt.tight_layout()
plt.show()
Adding Regression (Line of Best Fit)#
Regression allows us to guess a general trend.
The line gives a simple idea of 'on average, how does one value change with another?'
# Regression plot: Passengers vs Year
plt.figure(figsize=(8,5))
sns.regplot(x='Year', y='Passengers', data=data, scatter_kws={'color':'blue'}, line_kws={'color':'red'})
plt.title("Passengers Over Years (With Regression)")
plt.xlabel("Year")
plt.ylabel("Number of Passengers")
plt.show()
# Regression without dots: just show the trend
plt.figure(figsize=(8,5))
sns.regplot(x='Year', y='Passengers', data=data, scatter=False, color='green')
plt.title("Trend Line Only: Year vs Passengers")
plt.xlabel("Year")
plt.ylabel("Number of Passengers")
plt.show()
What is a Pairplot?#
A pairplot lets us compare all variable pairs at once.
We see different scatter plots and the shape of each column's values.
It works best for datasets with several columns.
# Create a mini-dataset with passengers by year, month, count
df = data[['Year','Month_num','Passengers']]
# Show a sample
df.head()
# Basic pairplot
sns.pairplot(df)
plt.suptitle("Pairplot: Year, Month, Passengers", y=1.02)
plt.show()
# Highlight pairplot by color (hue)
df['Decade'] = (df['Year']//10)*10
sns.pairplot(df, hue='Decade', palette='mako')
plt.suptitle("Pairplot Colored by Decade", y=1.02)
plt.show()
Real-world Use: Explore Weather Data#
Let us try another time series: daily minimum temperatures.
We will find patterns in how temperature changes with time.
# Load the daily minimum temperatures dataset
temp_url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv"
temp = pd.read_csv(temp_url)
print('Shape:', temp.shape)
temp.head()
# Plot: Temperature over time
plt.figure(figsize=(12,5))
plt.plot(temp['Date'], temp['Temp'], color='orange')
plt.xlabel('Date')
plt.ylabel('Temperature (C)')
plt.title('Daily Minimum Temperatures Over Time')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Regression plot: Temperature by Day-of-Year
temp['Date'] = pd.to_datetime(temp['Date'])
temp['DayOfYear'] = temp['Date'].dt.dayofyear
plt.figure(figsize=(8,5))
sns.regplot(x='DayOfYear', y='Temp', data=temp, scatter_kws={'s':1}, line_kws={'color':'red'})
plt.title('Temperature Trend Within the Year')
plt.xlabel('Day of Year (1-366)')
plt.ylabel('Minimum Temperature (C)')
plt.show()
Mini-Project: Exploring Your Own Data#
Now, let us try making a relationship plot with your own ideas or numbers!
You can use input values below.
# Input your two lists of numbers
x_vals = input("Enter at least 5 numbers, separated by commas, for X: ")
y_vals = input("Enter at least 5 numbers, separated by commas, for Y: ")
x = [float(x) for x in x_vals.split(',')]
y = [float(y) for y in y_vals.split(',')]
plt.scatter(x, y)
plt.title("Your Custom Scatter Plot")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()
Optimizations and Best Practices#
Use clear labels for axis names and titles.
Always preview your data before plotting.
If you have many points, lower dot size or use alpha for better visibility.
Check for missing or strange values that may confuse your results.
# Troubleshooting: what if your plot does not show?
print("Troubleshooting tips:")
print("- Check that you included plt.show()")
print("- Make sure your input data is numeric")
print("- Look for typos in column names")
print("- Run code cells in order, from top to bottom")
print("- If you see blank, try rerunning that cell or restarting the runtime")
Extra Tips#
Try switching plot types for new insights.
Use hue and style in seaborn plots to show categories clearly.
For huge datasets, sample smaller pieces to keep plots readable.
Check seaborn's documentation for even more options and examples.
Challenge: What Could You Explore Next?#
Try plotting passengers vs month for part of the data.
Make a pairplot with more weather columns if available.
Gather your own data and make a relationship plot from scratch.
Be creative and have fun discovering patterns!
Quick Recap#
You learned how to:
- Draw scatter plots to see connections.
- Add regression lines for trends.
- Use pairplots for broader views.
- Make cool plots with real data.
You are ready to spot patterns in your own projects!
Thanks and Next Steps#
Thank you for following along!
Try out more datasets or share your plots online.
If this helped you, consider subscribing and liking the video for more friendly Python tutorials!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



