Mathew K Analytics

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…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Welcome: 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()
Shape: (144, 2)
Month Passengers
0 1949-01 112
1 1949-02 118
2 1949-03 132
3 1949-04 129
4 1949-05 121
# 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()
No description has been provided for this image

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()
No description has been provided for this image
# 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()
No description has been provided for this image

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()
No description has been provided for this image
# 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()
No description has been provided for this image

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()
Year Month_num Passengers
0 1949 1 112
1 1949 2 118
2 1949 3 132
3 1949 4 129
4 1949 5 121
# Basic pairplot
sns.pairplot(df)
plt.suptitle("Pairplot: Year, Month, Passengers", y=1.02)
plt.show()
No description has been provided for this image
# 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()
No description has been provided for this image

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()
Shape: (3650, 2)
Date Temp
0 1981-01-01 20.7
1 1981-01-02 17.9
2 1981-01-03 18.8
3 1981-01-04 14.6
4 1981-01-05 15.8
# 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()
No description has been provided for this image
# 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()
No description has been provided for this image

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()
No description has been provided for this image

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")
Troubleshooting tips:
- Check that you included plt.show()
- Make sure your input data is numeric
- Look for typos in column names
- Run code cells in order, from top to bottom
- 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?#

  1. Try plotting passengers vs month for part of the data.

  2. Make a pairplot with more weather columns if available.

  3. 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.