Spatial Clustering: DBSCAN, K-Means, and Cluster Analysis

Spatial Clustering: DBSCAN, K-Means, and Cluster Analysis

A taxi company once showed me a map of a million pickup points and asked a reasonable question: “Where are our natural demand zones?” The map was a solid black smear. No human eye could separate one zone from another. But a few lines of code later, the cloud resolved into about thirty clear groups, a dense knot at the station, a long ribbon along the waterfront, a scatter of small pockets around the hospitals. The company redrew its dispatch areas that week.

What produced those groups was cluster analysis: algorithms that look at data and find groups of similar things on their own. In GIS, “similar” can mean close together, or similar in attributes, or both. It is one of the most practical techniques in the field, and one of the most misunderstood, because “clustering” means different things to different people. A statistician talking about hot spots and a data scientist running K-Means are doing quite different jobs.

In this guide I’ll clarify the vocabulary, explain how the main algorithms, K-Means, DBSCAN and their relatives, work, show how to run them correctly on geographic data, and explain how to judge whether the groups you found mean anything.

Illustration: K-means splits the data into compact groups; DBSCAN follows density, finds shapes and flags noise.
K-means splits the data into compact groups; DBSCAN follows density, finds shapes and flags noise.

Two Meanings of “Spatial Clustering”

Before any algorithm, let’s separate two families of methods that often share the same name.

1. Statistical cluster detection

These methods test whether a pattern of values is more clustered than random, and locate significant clusters. They answer: is there a cluster here, statistically? Examples are Getis-Ord Gi* and Local Moran’s I, described in Hotspot Analysis with Getis-Ord Gi* Explained and Spatial Autocorrelation and Moran’s I Explained. They have a null hypothesis, p-values and confidence levels.

2. Clustering algorithms (unsupervised learning)

These methods partition data into groups, according to some definition of similarity. They answer: how can I divide these points or areas into meaningful groups? They don’t test significance. They simply group. Examples are K-Means, DBSCAN, hierarchical clustering and their variants. This article focuses on this family, with a short bridge to the first.

A useful rule: statistical methods tell you whether clustering exists; algorithms tell you what the groups are. Often you use both.


What Do You Cluster? Three Kinds of Input

  • Point locations only: cluster by proximity. Taxi pickups, crime incidents, tree locations, photographs, shops. The question is geographic: where are the concentrations?
  • Attributes only, on areas or features: cluster by similarity of characteristics, such as grouping districts by their demographic profile. Location doesn’t enter the calculation, though you can map the result.
  • Locations and attributes together: cluster by both, finding areas that are close and similar. This is called spatially constrained or regionalization.

Keeping these apart helps you choose the right tool, and avoid common errors.


Why Clustering Is Useful

  • Find demand zones, service areas or markets from point data.
  • Detect concentrations of incidents: accidents, crimes, disease cases, fires.
  • Group similar places: typologies of neighborhoods, climate zones, soil types, land use patterns.
  • Reduce complexity: summarize thousands of points by a few representative groups.
  • Generate hypotheses: discover structures you didn’t anticipate.
  • Prepare data for other analyses, such as defining territories or regions.
  • Detect outliers and noise: isolate points that belong to no group.

K-Means: Partitioning Into K Groups

The idea

K-Means is the best-known clustering algorithm. You tell it how many groups you want, k, and it divides the data accordingly.

  1. Choose k initial centers (centroids), often at random or with a smart initialization.
  2. Assign every point to its nearest centroid.
  3. Recompute each centroid as the mean position of its assigned points.
  4. Repeat steps 2 and 3 until the assignments stop changing.

The result: k groups, each represented by a center, with every point belonging to exactly one.

Strengths

  • Fast and scalable, even to millions of points.
  • Simple to understand and implement.
  • Produces compact, similar-sized groups with clear centers.
  • Useful for territory design and for summarizing data by representative locations, such as choosing k warehouse locations.

Weaknesses

  • You must choose k in advance, though methods exist to guide you.
  • Assumes roughly round, similarly sized clusters. It struggles with elongated, curved or very different-sized groups.
  • Sensitive to outliers. A few extreme points pull centroids away.
  • Assigns every point to a cluster, even noise.
  • Results depend on the initialization, so run it several times.
  • Uses Euclidean distance, which is appropriate only in a projected CRS. On raw latitude and longitude, distances are distorted, especially at high latitudes. See Map Projections: How to Choose the Right One.

Choosing k

  • Elbow method: run K-Means for k = 2, 3, 4, and so on, and plot the total within-cluster variation. The “elbow”, where improvement slows, suggests a reasonable k.
  • Silhouette score: measures how well each point fits its cluster compared with neighboring clusters, from -1 to 1. Choose the k with the highest average silhouette.
  • Domain logic: sometimes k is a decision, such as “we have five depots”.

DBSCAN: Finding Clusters by Density

The idea

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) defines a cluster as a dense region of points, separated from other dense regions by sparse ones. It needs no k. Instead it uses two parameters:

  • eps (epsilon): the radius of a neighborhood around each point.
  • minPts (min_samples): the minimum number of points required within that radius for a region to count as dense.

Each point is classified as one of three types:

  • Core point: has at least minPts points (including itself) within eps. The heart of a cluster.
  • Border point: within eps of a core point, but doesn’t have enough neighbors itself. The edge of a cluster.
  • Noise point: neither. An outlier, left unassigned.

A cluster grows by connecting core points that lie within eps of each other, and then attaching their border points.

Strengths

  • Finds clusters of arbitrary shape: ribbons, rings, irregular blobs.
  • Doesn’t need the number of clusters in advance.
  • Identifies noise explicitly, marking isolated points as outliers rather than forcing them into groups.
  • Robust to outliers.
  • A natural fit for geographic point data, where density is often the very thing you care about.

Weaknesses

  • Sensitive to eps and minPts, which require thought.
  • Struggles with clusters of very different density. One eps can’t fit both a dense city center and a sparse suburb.
  • Distance units matter. Eps must be in the units of your data, so a projected CRS in meters, or a proper geographic distance.
  • Can be slow on huge datasets, unless an efficient spatial index is used.
  • No cluster centers or hierarchy, only groups.

Choosing eps and minPts

  • Think about the real world. What distance defines “close” for your problem? 200 meters between incidents? 50 meters between trees?
  • minPts: a rule of thumb is at least the number of dimensions plus one, with larger values, such as 5 to 20, for noisy or large data. For two-dimensional spatial data, 4 or more is a common minimum.
  • k-distance plot: for each point, compute the distance to its k-th nearest neighbor (k = minPts), sort the values and plot them. The “knee” of the curve suggests a good eps.
  • Try several values and check the results on a map. Stable clusters across reasonable settings are more convincing.

Other Algorithms Worth Knowing

HDBSCAN

A hierarchical extension of DBSCAN that handles varying density, producing clusters at multiple density levels and requiring mostly a minimum cluster size. A strong choice when a single eps doesn’t work.

OPTICS

Orders points to reveal cluster structure at many density levels, without committing to one eps. It produces a “reachability plot” from which clusters can be extracted.

Hierarchical (agglomerative) clustering

Starts with each point as its own cluster and repeatedly merges the closest pair, building a tree called a dendrogram. You choose where to cut the tree to get your clusters. Good for small to medium datasets and for seeing structure at several scales, but computationally heavy on large data.

K-Medoids

Like K-Means, but the centers are actual data points (medoids), which makes it more robust to outliers and useful when the center must be a real location, such as an existing facility.

Gaussian mixture models

Model the data as a mixture of probability distributions, giving soft assignments (probabilities of belonging to each cluster) and elliptical shapes.

Space-time clustering

Extensions such as ST-DBSCAN and scan statistics add the time dimension, finding clusters of events that are close in both space and time, such as outbreaks or burglary waves.

Spatially constrained clustering (regionalization)

When you want groups of contiguous areas with similar attributes, the algorithm must respect geography. Methods such as SKATER, AZP and Max-p build regions from polygons so that each region is connected and internally homogeneous. They’re used to design service districts, statistical regions and sales territories.

Kernel density estimation

Not a clustering algorithm, but often used alongside: it turns points into a smooth density surface, which shows concentrations visually. It helps explore and choose parameters, but doesn’t assign points to groups.


Comparing the Main Methods

FeatureK-MeansDBSCANHDBSCANHierarchical
Number of clustersYou choose kFound automaticallyFound automaticallyYou cut the tree
Cluster shapeRound, compactArbitraryArbitraryDepends on linkage
Handles noiseNoYesYesNot directly
Varying densityPoorlyPoorlyWellModerately
Key parameterskeps, minPtsminimum cluster sizeLinkage, cut level
Speed on large dataVery fastFast with an indexModerateSlow
Typical GIS useTerritories, zonesHot zones of eventsComplex density patternsTypologies of areas

Running Clustering on Geographic Data

A critical point: distances and coordinates

Most algorithms rely on distance, so how you represent location matters.

  • Use a projected CRS in meters for local and regional data, and cluster on the X and Y coordinates. Distances are then meaningful and eps is in meters.
  • For large areas in latitude and longitude, use a haversine distance, which measures along the curved Earth, and express eps in radians, as in the example below.
  • Don’t cluster raw latitude and longitude with Euclidean distance over large areas or high latitudes. A degree of longitude shrinks as you move toward the poles.
  • When mixing attributes with coordinates, standardize all variables to comparable scales, or one will dominate. A distance in meters and an income in thousands are not commensurable.

In QGIS

Recent versions of QGIS include clustering tools in the Processing Toolbox, such as DBSCAN clustering and K-means clustering, which add a cluster ID to your points. Check your version, and see Best GIS Plugins for QGIS for extensions.

In ArcGIS Pro

The Spatial Statistics toolbox includes Density-based Clustering (with DBSCAN, HDBSCAN and OPTICS methods), Multivariate Clustering, Spatially Constrained Multivariate Clustering and Cluster and Outlier Analysis.

In Python (scikit-learn)

DBSCAN with geographic distance: cluster points given as latitude and longitude, finding groups within about 500 meters of each other, with at least 10 points:

import numpy as np
import pandas as pd
from sklearn.cluster import DBSCAN

pts = pd.read_csv("incidents.csv")            # columns: lat, lon
coords = np.radians(pts[["lat", "lon"]].values)

kms_per_radian = 6371.0088
eps = 0.5 / kms_per_radian                    # 0.5 km expressed in radians

db = DBSCAN(eps=eps, min_samples=10,
            algorithm="ball_tree", metric="haversine").fit(coords)

pts["cluster"] = db.labels_                   # -1 means noise
print(pts["cluster"].value_counts())

K-Means on projected coordinates: assuming the points are in a projected CRS, in meters:

import numpy as np
import geopandas as gpd
from sklearn.cluster import KMeans

gdf = gpd.read_file("points.gpkg").to_crs(epsg=3857)   # use a suitable local CRS
X = np.column_stack([gdf.geometry.x, gdf.geometry.y])

kmeans = KMeans(n_clusters=5, n_init=10, random_state=42).fit(X)
gdf["cluster"] = kmeans.labels_
centers = kmeans.cluster_centers_

(EPSG:3857 is used here only to keep the example short. In real work, choose a projected CRS suited to your area.) For the wider toolkit, see Geospatial Development & Automation: The Ultimate Guide.

In R

Packages such as dbscan, cluster and sf, together with base kmeans and hclust, cover the whole family.


Evaluating Clusters: Are They Meaningful?

Algorithms always return something. The hard part is deciding whether it is worth anything.

Internal measures

  • Silhouette score: how cohesive and well separated the clusters are.
  • Within-cluster sum of squares: compactness of the groups (used in the elbow method).
  • Davies-Bouldin and Calinski-Harabasz indices: other measures of separation and compactness.

These measures assess the geometry of the groups, not their usefulness.

Stability

Run the algorithm with different parameters, different random starts, or subsamples of the data. Clusters that persist are likely real. Clusters that vanish are probably artifacts.

Visual inspection

Map the clusters over a basemap, and ask: do they make sense? Do they correspond to places you recognize, such as a market, a station or a school? Are there suspicious shapes caused by data collection, for example points lined up along a road because that is where observers walked?

Validation against knowledge

Compare with known categories, field observations or independent datasets. If you can’t explain what a cluster is, you haven’t finished.

Statistical testing

Remember that algorithms don’t test significance. If the claim is “events are clustered”, support it with a statistical test, such as Moran’s I for values, or a point pattern test like Ripley’s K or nearest neighbor analysis. See Spatial Statistics for GIS: Complete Guide.


A Worked Example: Delivery Hubs

Question: a logistics company wants to place five micro-hubs to serve a city’s 40,000 yearly deliveries. Where?

  1. Collect the delivery locations, and geocode where needed. See Geocoding: How to Convert Addresses to Coordinates.
  2. Reproject to a suitable projected CRS, in meters.
  3. Clean the data: remove duplicates and obvious errors.
  4. Explore: make a density map to see the general pattern.
  5. Run K-Means with k = 5, repeated with multiple starts, to get five balanced zones and their centers. Optionally weight points by delivery volume.
  6. Snap the centers to real, available sites nearby, perhaps using K-Medoids or by checking land use and rents.
  7. Evaluate with real travel: the K-Means centers use straight-line distance, so test the candidate hubs with network analysis to compute actual travel times. See Network Analysis and Route Optimization.
  8. Compare alternatives: try k = 4 and k = 6. How do average travel times change?
  9. Decide with the business constraints, and document the method.

Notice the division of labor: the algorithm suggests a structure, while network analysis, local knowledge and constraints refine it into a decision.


Common Mistakes

  • Using K-Means when clusters are not compact, or when noise is significant. Consider DBSCAN or HDBSCAN.
  • Clustering raw latitude and longitude with Euclidean distance over large areas.
  • Choosing eps blindly, without a k-distance plot or domain reasoning.
  • Ignoring noise, and forcing every point into a cluster.
  • Forgetting to standardize variables when mixing different scales.
  • Treating the clusters as facts, not as one possible partition. Different parameters give different answers.
  • Confusing density with risk. Dense points follow population. Normalize when comparing places.
  • Mistaking clustering algorithms for statistical tests. They find groups, not significance.
  • Not checking stability.
  • Clustering data collected unevenly. If observers sampled only along certain roads, clusters will reflect the sampling, not the phenomenon.
  • Reporting clusters without their parameters, which makes the result irreproducible.
  • Leaving out privacy. Clusters of individual-level data, such as patient locations, can reveal sensitive information. Aggregate before sharing.

Choosing Between Methods: A Quick Guide

  • You want a fixed number of balanced zones or centers: K-Means (or K-Medoids if centers must be real points).
  • You want to find dense concentrations and flag outliers: DBSCAN.
  • Density varies widely across the area: HDBSCAN or OPTICS.
  • You want to see structure at several scales, with a manageable amount of data: hierarchical clustering.
  • You want contiguous regions of similar areas: spatially constrained clustering.
  • You want to know whether clusters are statistically significant: hot spot analysis or Local Moran’s I.
  • You want to find clusters in space and time: space-time scan statistics or ST-DBSCAN.

Final Thoughts

Cluster analysis turns an overwhelming cloud of points into a few comprehensible groups, and that is a gift to any analyst. But it is also a tool that will happily deliver a confident answer to a badly posed question. The algorithm doesn’t know what a neighborhood is, what a market is, or what a crime hot spot means. You supply the meaning, by choosing the right method for the shape of your data, setting parameters with real-world reasoning, and checking the result against what you know.

Take a set of points you understand well, such as shops, accidents or photos, and run both K-Means and DBSCAN on them. Map the results side by side. Seeing how differently they carve up the same data teaches the most important lesson in this field: every clustering is a hypothesis, not a discovery.

Where to go next: return to Spatial Analysis in GIS: Complete Guide to see where clustering fits within the wider toolbox, and to Spatial Statistics for GIS: Complete Guide for the statistical tests that complement it.

Rachid Khouri

Rachid Khouri

Rachid Khouri is a CAD, BIM and GIS professional, Autodesk Authorized Developer, trainer and technical author with more than 30 years of experience, working with AutoCAD since 1992. He founded GISauthority.com to share practical guidance on GIS and spatial technologies.