🗺️ Calculating and visualising population density¶
ipyleaflet + GeoPandas | Google Colab
This notebook does the same task as the PyQGIS example — calculating population density — in a pure Python environment, on Google Colab.
📐 Formula¶
$$D = \frac{P}{A}$$
where:
- D — population density (people/km²)
- P — population count (
Mosaxl_200) - A — area in square kilometres (
area_km)
🔧 Libraries used¶
| Library | Purpose |
|---|---|
geopandas |
processing spatial data (the QGIS equivalent) |
ipyleaflet |
an interactive map in Jupyter/Colab |
branca |
a colour scale (colormap) for the legend |
pandas |
the attribute table |
numpy |
numeric calculations |
📦 Step 1 — installing the libraries¶
On Google Colab,
geopandasandipyleafletneed to be installed first.
# installing the libraries on Google Colab
!pip install geopandas ipyleaflet branca --quiet
📥 Step 2 — importing the libraries¶
import geopandas as gpd
import pandas as pd
import numpy as np
import json
import requests
import ipyleaflet
from ipyleaflet import (
Map, GeoJSON, Choropleth, LegendControl,
WidgetControl, LayersControl, basemaps
)
from ipywidgets import HTML, Output
import branca.colormap as cm
print(f"✅ geopandas v{gpd.__version__}")
print(f"✅ ipyleaflet v{ipyleaflet.__version__}")
print(f"✅ pandas v{pd.__version__}")
🗺️ Step 3 — loading the data of Georgia's municipalities¶
We use the GeoJSON of Georgia's level-2 administrative units from the GADM (Global Administrative Areas) database.
In this example synthetic population data (Mosaxl_200) is added, as in the PyQGIS example.
# -------------------------------------------------------
# loading the GeoJSON of Georgia's municipalities
# GADM v4.1 — Georgia, Admin Level 2 (municipalities)
# -------------------------------------------------------
GEOJSON_URL = (
"https://raw.githubusercontent.com/nvkelso/natural-earth-vector/"
"master/geojson/ne_10m_admin_1_states_provinces.geojson"
)
# downloading and filtering for Georgia
gdf_world = gpd.read_file(GEOJSON_URL)
gdf = gdf_world[gdf_world['admin'] == 'Georgia'].copy()
gdf = gdf.reset_index(drop=True)
print(f"📌 Number of features loaded: {len(gdf)}")
print(f"📌 CRS: {gdf.crs}")
gdf[['name', 'geometry']].head()
🔢 Step 4 — adding synthetic population data¶
The Mosaxl_200 field, as in the PyQGIS example — population data for the 2000s.
For a real project this field should exist in the GeoPackage/Shapefile.
# -------------------------------------------------------
# synthetic population data (Mosaxl_200)
# estimated population of Georgia's regions, 2002
# -------------------------------------------------------
np.random.seed(42)
# estimated values of Georgia's real regional population
population_map = {
"Tbilisi": 1081679,
"Adjara": 376016,
"Guria": 113350,
"Imereti": 699666,
"Kakheti": 407182,
"Kvemo Kartli": 497531,
"Mtskheta-Mtianeti": 125141,
"Racha-Lechkhumi and Kvemo Svaneti": 50969,
"Samegrelo-Zemo Svaneti": 466.100,
"Samtskhe-Javakheti": 207598,
"Shida Kartli": 314801,
"Abkhazia": 215272,
"South Ossetia": 70000
}
def assign_population(name):
"""Assign population by name, otherwise a random value"""
for key, val in population_map.items():
if key.lower() in str(name).lower() or str(name).lower() in key.lower():
return int(val)
return np.random.randint(50_000, 500_000)
gdf['Mosaxl_200'] = gdf['name'].apply(assign_population)
print("✅ The Mosaxl_200 field has been added")
gdf[['name', 'Mosaxl_200']].sort_values('Mosaxl_200', ascending=False)
📐 Step 5 — calculating the area and the population density¶
The PyQGIS equivalent — $area, "area"/1000000, "Mosaxl_200"/area_km:
# In QGIS:
expr1 = QgsExpression('$area') # sq. metres
expr2 = QgsExpression('"area"/1000000') # sq. km
expr3 = QgsExpression('"Mosaxl_200"/area_km') # density
# In GeoPandas it looks like this:
gdf['area'] = gdf.to_crs(epsg=32638).area # sq. metres
gdf['area_km'] = gdf['area'] / 1_000_000 # sq. km
gdf['simwidrove'] = gdf['Mosaxl_200'] / gdf['area_km'] # people/km²
# -------------------------------------------------------
# calculating the area
# EPSG:32638 — UTM Zone 38N (suitable for Georgia)
# -------------------------------------------------------
# keeping the original CRS (WGS84 — for ipyleaflet)
gdf_wgs84 = gdf.copy()
# calculating the area in a projected system (sq. metres)
gdf_projected = gdf.to_crs(epsg=32638)
gdf_wgs84['area'] = gdf_projected.area # expr1: $area
gdf_wgs84['area_km'] = gdf_wgs84['area'] / 1_000_000 # expr2: "area"/1000000
gdf_wgs84['simwidrove'] = ( # expr3: "Mosaxl_200"/area_km
gdf_wgs84['Mosaxl_200'] / gdf_wgs84['area_km']
)
print("✅ The fields have been calculated:")
print(f" area — area in square metres")
print(f" area_km — area in square kilometres")
print(f" simwidrove — population density (people/km²)")
print()
# the results table
result_df = gdf_wgs84[['name', 'Mosaxl_200', 'area_km', 'simwidrove']].copy()
result_df['area_km'] = result_df['area_km'].round(2)
result_df['simwidrove'] = result_df['simwidrove'].round(2)
result_df.sort_values('simwidrove', ascending=False).reset_index(drop=True)
🗺️ Step 6 — an ipyleaflet choropleth map¶
Visualisation with a choropleth map — the density value shown by colour intensity.
- 🟡 light yellow → low density
- 🔴 dark red → high density
On hover, the municipality's name and density appear.
# -------------------------------------------------------
# preparing the GeoJSON for ipyleaflet
# -------------------------------------------------------
# converting the GeoDataFrame to GeoJSON
geojson_data = json.loads(gdf_wgs84.to_json())
# a density dictionary (for the choropleth)
choro_data = dict(
zip(
gdf_wgs84['name'].astype(str),
gdf_wgs84['simwidrove'].round(2)
)
)
print(f"✅ The GeoJSON is ready — {len(geojson_data['features'])} features")
print("\n📊 Density values (people/km²):")
for name, val in sorted(choro_data.items(), key=lambda x: x[1], reverse=True):
bar = "█" * min(int(val / 50), 30)
print(f" {name:<40} {val:>8.1f} {bar}")
# -------------------------------------------------------
# creating the ipyleaflet choropleth map
# -------------------------------------------------------
# the colour scale (YlOrRd — yellow → orange → red)
colormap = cm.LinearColormap(
colors=['#ffffb2', '#fecc5c', '#fd8d3c', '#f03b20', '#bd0026'],
vmin=gdf_wgs84['simwidrove'].min(),
vmax=gdf_wgs84['simwidrove'].quantile(0.95), # clipping outliers
caption='Population density (people/km²)'
)
# creating the map — centred on Georgia
m = Map(
center=(42.0, 43.5),
zoom=7,
basemap=basemaps.CartoDB.Positron,
scroll_wheel_zoom=True
)
# the choropleth layer
choropleth = Choropleth(
geo_data=geojson_data,
choro_data=choro_data,
colormap=colormap,
key_on='feature.properties.name',
border_color='white',
style={
'fillOpacity': 0.75,
'weight': 1.5,
'dashArray': '3'
},
hover_style={
'fillOpacity': 0.95,
'weight': 3,
'dashArray': '0'
},
name='Population density'
)
m.add_layer(choropleth)
# the colour scale legend
colormap.add_to(m)
# the layer control
m.add_control(LayersControl(position='topright'))
# the title
title_html = HTML(
value="""
<div style='
background: rgba(255,255,255,0.92);
padding: 10px 16px;
border-radius: 8px;
border-left: 4px solid #bd0026;
font-family: sans-serif;
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
'>
<b style='font-size:14px;'>🗺️ Georgia</b><br>
<span style='font-size:12px; color:#555;'>Population density — people/km²</span>
</div>
"""
)
m.add_control(WidgetControl(widget=title_html, position='topleft'))
# the hover info panel
info_html = HTML(
value="<div style='font-family:sans-serif; font-size:12px; color:#777; padding:6px;'>hover over a region</div>"
)
info_widget = WidgetControl(widget=info_html, position='bottomleft')
m.add_control(info_widget)
def on_hover(event, feature, **kwargs):
"""Show the info on hover"""
name = feature['properties'].get('name', '?')
density = choro_data.get(name, 0)
area = gdf_wgs84.loc[gdf_wgs84['name'] == name, 'area_km'].values
pop = gdf_wgs84.loc[gdf_wgs84['name'] == name, 'Mosaxl_200'].values
area_str = f"{area[0]:,.0f}" if len(area) else "?"
pop_str = f"{pop[0]:,}" if len(pop) else "?"
info_html.value = f"""
<div style='
background: rgba(255,255,255,0.95);
padding: 10px 14px;
border-radius: 6px;
font-family: sans-serif;
font-size: 12px;
border-left: 3px solid #bd0026;
min-width: 180px;
'>
<b style='font-size:13px;'>{name}</b><br>
👥 Population: <b>{pop_str}</b><br>
📐 Area: <b>{area_str} km²</b><br>
📊 Density: <b>{density:.1f} people/km²</b>
</div>
"""
choropleth.on_hover(on_hover)
print("✅ The map is ready — you will see the visualisation below")
m
Population density — people/km²
👥 Population: {pop_str}
📐 Area: {area_str} km²
📊 Density: {density:.1f} people/km²
📊 Step 7 — the results table¶
The equivalent of the PyQGIS attribute table — all the calculated attributes.
# -------------------------------------------------------
# the results table — attribute table (the QGIS equivalent)
# -------------------------------------------------------
display_df = gdf_wgs84[[
'name', 'Mosaxl_200', 'area', 'area_km', 'simwidrove'
]].copy()
display_df.columns = [
'Region', 'Population (Mosaxl_200)',
'Area (m²)', 'Area (km²)', 'Density (people/km²)'
]
display_df['Area (m²)'] = display_df['Area (m²)'].apply(lambda x: f"{x:,.0f}")
display_df['Area (km²)'] = display_df['Area (km²)'].apply(lambda x: f"{x:,.2f}")
display_df['Density (people/km²)'] = display_df['Density (people/km²)'].apply(lambda x: f"{x:.2f}")
display_df['Population (Mosaxl_200)'] = display_df['Population (Mosaxl_200)'].apply(lambda x: f"{x:,}")
display_df.reset_index(drop=True, inplace=True)
display_df
💾 Step 8 — saving the results¶
Exporting the calculated data in GeoJSON and CSV formats.
# -------------------------------------------------------
# exporting the results
# -------------------------------------------------------
# saving the GeoJSON (to open in QGIS)
export_cols = ['name', 'Mosaxl_200', 'area', 'area_km', 'simwidrove', 'geometry']
gdf_export = gdf_wgs84[export_cols].copy()
gdf_export.to_file('municipalitys_density.geojson', driver='GeoJSON')
print("✅ GeoJSON saved: municipalitys_density.geojson")
# saving the CSV (the attribute table)
csv_cols = ['name', 'Mosaxl_200', 'area', 'area_km', 'simwidrove']
gdf_wgs84[csv_cols].to_csv('municipalitys_density.csv', index=False, encoding='utf-8-sig')
print("✅ CSV saved: municipalitys_density.csv")
# downloading on Google Colab
try:
from google.colab import files
files.download('municipalitys_density.csv')
files.download('municipalitys_density.geojson')
print("📥 Downloading the files...")
except ImportError:
print("ℹ️ Not a Colab environment — the files are saved in the current directory")
📝 Summary — comparing PyQGIS and GeoPandas¶
| Operation | PyQGIS | GeoPandas (Colab) |
|---|---|---|
| Opening a layer | QgsProject.instance().mapLayersByName() |
gpd.read_file() |
| Adding a field | pv.addAttributes([QgsField(...)]) |
gdf['field'] = ... |
| Area | QgsExpression('$area') |
gdf.to_crs(32638).area |
| Area in km² | QgsExpression('"area"/1000000') |
gdf['area'] / 1_000_000 |
| Density | QgsExpression('"Mosaxl_200"/area_km') |
gdf['Mosaxl_200'] / gdf['area_km'] |
| Updating the attributes | layer.updateFeature(i) |
automatic (pandas) |
| Visualisation | QGIS Layer Styling | ipyleaflet.Choropleth |
| Export | Save As... | gdf.to_file() / df.to_csv() |
📌 Note: for a real project, the
Mosaxl_200field should be in a GeoPackage or Shapefile —gpd.read_file('Municipalitys.gpkg'), and every other step is used exactly like this.
osdoc.qgis.ge | PyQGIS course