Mathew K Analytics

Lesson 14 · Data visualisation in python

Introduction to Seaborn for Data Visualization with Built-in Python Datasets

In this lesson, we will explore Seaborn, a powerful Python library for visualizing data. You will learn how to load built-in datasets, create beautiful…

⬇ 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 to the Beginner's Guide to Seaborn!#

In this lesson, we will explore Seaborn, a powerful Python library for visualizing data.

You will learn how to load built-in datasets, create beautiful charts, and uncover patterns with simple code.

No prior experience needed. Let's get started!

# Let\'s set up our environment
import warnings
warnings.filterwarnings("ignore")
 
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt

# These libraries will help us explore and plot our data

What is Seaborn?#

Seaborn is a library in Python designed to make data visualization simple and attractive.

It works well with pandas DataFrames, which are tables of rows and columns.

With just a few lines of code, you can see patterns in your data.

# Let\'s view Seaborn\'s built-in datasets
print(sns.get_dataset_names())
['anagrams', 'anscombe', 'attention', 'brain_networks', 'car_crashes', 'diamonds', 'dots', 'dowjones', 'exercise', 'flights', 'fmri', 'geyser', 'glue', 'healthexp', 'iris', 'mpg', 'penguins', 'planets', 'seaice', 'taxis', 'tips', 'titanic']
# Let\'s load the \"flights\" dataset
flights = sns.load_dataset("flights")
 
# Show the top 5 rows
flights.head()
year month passengers
0 1949 Jan 112
1 1949 Feb 118
2 1949 Mar 132
3 1949 Apr 129
4 1949 May 121

Reading the flights table#

Each row in the table shows a month and year, along with the number of airline passengers.

This is a small time series, which means it shows numbers changing over time.

Next, we will look at the size and a simple preview.

# Show the shape: rows and columns
print("Shape:", flights.shape)
# Show quick summary of the dataset
print("\nInfo:")
flights.info()
Shape: (144, 3)

Info:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 144 entries, 0 to 143
Data columns (total 3 columns):
 #   Column      Non-Null Count  Dtype   
---  ------      --------------  -----   
 0   year        144 non-null    int64   
 1   month       144 non-null    category
 2   passengers  144 non-null    int64   
dtypes: category(1), int64(2)
memory usage: 2.9 KB
# Plot how the number of passengers changes over time
plt.figure(figsize=(10,4))
sns.lineplot(data=flights, x="year", y="passengers")
plt.title("Passengers per Year")
plt.show()
No description has been provided for this image

Exploring Variables#

The 'flights' dataset has three columns: 'year', 'month', and 'passengers'.

'year' and 'month' tell us when. 'passengers' is a number count.

Understanding variables helps us choose visualizations.

# See all unique months in the dataset
print(flights["month"].unique())

# How many records for each month?
print(flights["month"].value_counts())
['Jan', 'Feb', 'Mar', 'Apr', 'May', ..., 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
Length: 12
Categories (12, object): ['Jan', 'Feb', 'Mar', 'Apr', ..., 'Sep', 'Oct', 'Nov', 'Dec']
month
Jan    12
Feb    12
Mar    12
Apr    12
May    12
Jun    12
Jul    12
Aug    12
Sep    12
Oct    12
Nov    12
Dec    12
Name: count, dtype: int64
# Let\'s plot passengers per month for a year
data_1950 = flights[flights["year"]==1950]
sns.barplot(data=data_1950, x="month", y="passengers")
plt.title("Passengers per Month in 1950")
plt.show()
No description has been provided for this image
# What if we want to see change across all years by month?
pivot_data = flights.pivot(index="month", columns="year", values="passengers")
sns.heatmap(pivot_data, cmap="YlGnBu")
plt.title("Monthly Airline Passengers (1949-1960)")
plt.show()
No description has been provided for this image
# Check for any missing values in the dataset
print(flights.isnull().sum())
year          0
month         0
passengers    0
dtype: int64
# Summary statistics for passengers
print(flights["passengers"].describe())
count    144.000000
mean     280.298611
std      119.966317
min      104.000000
25%      180.000000
50%      265.500000
75%      360.500000
max      622.000000
Name: passengers, dtype: float64
# Filter the data: find months with over 400 passengers
busy = flights[flights["passengers"]>400]
print(busy.head())
     year month  passengers
90   1956   Jul         413
91   1956   Aug         405
101  1957   Jun         422
102  1957   Jul         465
103  1957   Aug         467

Combining Data#

You can join or combine datasets if you want to add new information.

For example, you could add a new column for holidays or special events.

Let's see a small example next.

# Add a new column: Is Summer?
flights["is_summer"] = flights["month"].isin(["June","July","August"])
print(flights[["month", "is_summer"]].head(12))
   month  is_summer
0    Jan      False
1    Feb      False
2    Mar      False
3    Apr      False
4    May      False
5    Jun      False
6    Jul      False
7    Aug      False
8    Sep      False
9    Oct      False
10   Nov      False
11   Dec      False
# Mini-project: Visualize only the summer months
summer_flights = flights[flights["is_summer"]]
sns.lineplot(data=summer_flights, x="year", y="passengers", ci=None)
plt.title("Summer Passengers Over the Years")
plt.show()
No description has been provided for this image
# Save a chart to a file
plt.figure(figsize=(8,4))
sns.lineplot(data=flights, x="year", y="passengers")
plt.title("Passengers per Year")
plt.savefig("passengers_per_year.png")
plt.close()
# Troubleshooting: What if you make a typo?
try:
    sns.lineplot(data=flights, x="yeer", y="passengers")
except Exception as e:
    print("Error:", e)
    
Error: Could not interpret value `yeer` for `x`. An entry with this name does not appear in `data`.
# User input: Let\'s let you pick a year to visualize!
user_year = input("Type a year between 1949 and 1960: ")
selected = flights[flights["year"]==int(user_year)]
sns.barplot(data=selected, x="month", y="passengers")
plt.title(f"Airline Passengers in {user_year}")
plt.show()
No description has been provided for this image

Recap and Practice#

You have learned how to use Seaborn to work with built-in datasets, make line and bar charts, and find data patterns.

Try exploring other datasets in Seaborn. Change filters and create your own plots.

Visualization helps you see stories in data more clearly.

Thanks for Learning with Us!#

If you enjoyed this lesson, hit Like and Subscribe for more Python tips and tutorials.

Happy coding and keep exploring data with Seaborn!

See you next time!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.