Lesson 32 · Data visualisation in python
Geospatial Analysis Case Study: Mapping and Visualizing Real-World Location Data
In this lesson, you will learn how to work with Python, explore real-world geospatial data, and visualize it using friendly tools. You do not need any…
- CourseData visualisation in python
- Lesson32 of 34
- Video14 min
- FormatJupyter notebook · 24 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbWelcome to Python Geospatial Mapping!#
In this lesson, you will learn how to work with Python, explore real-world geospatial data, and visualize it using friendly tools.
You do not need any programming experience, just curiosity!
We will build up step by step, from basic variables to mapping airline passenger flows.
import warnings; warnings.filterwarnings('ignore')
# This line tells Python to suppress warning messages.
# Warnings often show up when using data science tools.
# Keeping them hidden makes things less distracting for new users.
What is Geospatial Data?#
Geospatial data means information that has locations or coordinates attached to it.
Think of airline routes, city locations, or weather measurements. It helps us answer 'where' questions using data!
# Let us start with a simple variable.
city = "London"
print(city)
# Python stores text inside quote marks.
# You can also store numbers.
passengers = 250
print(passengers)
# Lists help us group many items. Let us list some major cities.
cities = ["London", "Paris", "New York", "Tokyo"]
print(cities)
# Access an item from a list using its position (starting from 0).
print(cities[1])
Real-World Data#
Now let us try working with real airline passenger data.
We will use a CSV file (a table of data) with months and the number of airline passengers. Then we will learn how to explore and plot it!
# Data setup
import pandas as pd
url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv"
df = pd.read_csv(url)
print("Shape:", df.shape)
print(df.head())
# Plot airline passenger counts to see patterns over time.
import matplotlib.pyplot as plt
df.plot(x="Month", y="Passengers", legend=False, title="Airline Passengers Over Time")
plt.ylabel("Passengers")
plt.show()
# Let us print the month with the highest passenger number.
max_row = df[df["Passengers"] == df["Passengers"].max()]
print("Busiest month:", max_row["Month"].values[0])
# Create a list of all months.
months = df["Month"].tolist()
print(months[:5]) # Show the first five months
# Calculate how many months had more than 400 passengers.
over_400 = df[df["Passengers"] > 400]
print("Months with over 400 passengers:", over_400.shape[0])
# Safe access: What if a month is missing in the data?
search_month = input("Enter a month (like 1950-08): ")
if search_month in months:
print("Yes,", search_month, "is in the airline data.")
else:
print("Sorry,", search_month, "is not in our list.")
# Add a new column to categorize each month as High or Low traffic.
df["TrafficLevel"] = ["High" if p > 400 else "Low" for p in df["Passengers"]]
print(df[["Month", "Passengers", "TrafficLevel"]].head())
# Remove a column if it is not needed anymore.
df = df.drop(columns=["TrafficLevel"])
print(df.head())
# Find and print basic statistics about the passenger numbers.
print("Average:", df["Passengers"].mean())
print("Minimum:", df["Passengers"].min())
print("Maximum:", df["Passengers"].max())
# Loop through each month and print when passengers were above 450.
for idx, row in df.iterrows():
if row['Passengers'] > 450:
print(row['Month'], 'had over 450 passengers.')
# Create a list of months that had less than 350 passengers.
low_months = [row['Month'] for idx, row in df.iterrows() if row['Passengers'] < 350]
print(low_months)
# Sort the data so busiest months appear first.
sorted_df = df.sort_values("Passengers", ascending=False)
print(sorted_df.head())
# Add together all passenger counts from 1955 onward.
from datetime import datetime
recent_mask = df["Month"].apply(lambda x: int(x.split('-')[0]) >= 1955)
recent_sum = df[recent_mask]["Passengers"].sum()
print("Total passengers from 1955 onward:", recent_sum)
# Mini-project Part 1: Rough map of monthly traffic ups and downs.
import numpy as np
plt.figure(figsize=(12,5))
plt.plot(df["Month"], df["Passengers"], label="Monthly Traffic", color="steelblue")
plt.scatter(df["Month"][::12], df["Passengers"][::12], color="firebrick", label="Year starts")
plt.xlabel("Month")
plt.ylabel("Passengers")
plt.xticks(df["Month"][::12], rotation=45)
plt.legend()
plt.title("Airline Traffic Seasonality (Year Starts Highlighted)")
plt.tight_layout()
plt.show()
# Mini-project Part 2: Map busiest months using world cities and simple coordinates.
world_cities = {
"London": (51.5074, -0.1278),
"Paris": (48.8566, 2.3522),
"New York": (40.7128, -74.0060),
"Tokyo": (35.6895, 139.6917),
}
busiest = sorted_df.iloc[0:4]["Month"].tolist()
print("Busiest months:", busiest)
# In a real map, we would plot world city coordinates!
for city, coords in world_cities.items():
print(f"{city}: Latitude {coords[0]}, Longitude {coords[1]}")
# Best practices: Always check for missing or strange numbers.
print("Any missing data?", df.isna().any().any())
print("Example data types:", df.dtypes.to_dict())
# Troubleshooting: Code sometimes gives an error.
try:
print(df["NonexistentColumn"].head())
except KeyError:
print('Oops! That column does not exist in this data.')
# Tips: Use the .info() and .describe() functions for a quick overview.
print(df.info())
print(df.describe())
# Challenge: Find the first month with fewer than 150 passengers.
for idx, row in df.iterrows():
if row['Passengers'] < 150:
print('First month with under 150 passengers:', row['Month'])
break
Recap: What Have You Learned?#
You loaded real geospatial data, explored lists and tables, made charts, filtered and mapped real numbers to real locations. You built mini projects and learned to troubleshoot along the way!
Keep building, and you will soon be a data explorer!
Thank You and Next Steps!#
If you enjoyed this lesson, like and subscribe for more beginner Python projects on this channel. Try out the bonus challenge: pick a new city or dataset and make your own plots!
See you in the next video!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



