Zonal Statistics
Calculate raster statistics within polygon zones
What Are Zonal Statistics?
Zonal statistics summarise the values of a raster within zones defined by a polygon (or, less commonly, another categorical raster). For each zone you compute aggregate statistics β mean, median, sum, min, max, standard deviation, count, majority class β over all the raster cells that fall inside that zone. The output is a table or an enriched polygon layer where every input polygon now carries the summary statistics of the underlying raster as attributes.
The Zonal Statistics tool on gis.tools loads a raster GeoTIFF and a polygon vector layer, computes per-polygon statistics in the browser, and writes the results back to the polygons. People search for "zonal statistics", "zonal stats raster polygon", "zonal stats qgis", "raster statistics within polygon", "extract raster values to polygons" and "average raster per polygon" because zonal statistics is one of the most heavily used operations in raster GIS, sitting at the intersection of remote sensing, ecology, planning, hydrology and any analysis that asks "what is the typical raster value inside this area?".
The operation is conceptually simple β take a raster, take some polygons, summarise β but a great deal of analytical insight depends on doing it correctly. The choice of statistic, how edge pixels are handled, whether the raster is continuous or categorical, and whether the zones overlap all matter.
How Zonal Statistics Work
The algorithm has two phases: identify which raster cells fall inside each polygon, then compute the requested statistic over those cells.
Phase 1: Cell Membership
For each polygon, the tool computes the bounding box, extracts the raster sub-array that intersects the bounding box, and tests each cell's centre against the polygon using a point-in-polygon algorithm. Cells whose centre is inside contribute to the polygon's statistics. This is the "centroid rule"; the alternative "all touched" rule includes any cell that intersects the polygon at all.
Phase 2: Statistic Computation
For each polygon's set of contributing cells, the tool computes the chosen aggregate(s):
- Mean / Sum: Single-pass arithmetic.
- Min / Max: Single-pass scan.
- Standard Deviation / Variance: Welford's algorithm for numerical stability.
- Median / Percentiles: Sort the values, pick the percentile.
- Majority / Minority / Unique: For categorical rasters, count occurrences and pick the most/least common, or list unique classes.
- Count: Number of contributing cells.
Multi-Band Handling
For multi-band rasters, statistics are computed independently per band. The output table has one column per (band x statistic) combination.
Nodata
Cells with nodata are excluded from the statistic. The contributing-cell count therefore measures how many valid cells the polygon contains.
Key Parameters and Options
Statistics Selection
Choose any combination of mean, median, sum, min, max, standard deviation, count, range, majority, minority, unique value count and percentiles. Common defaults are mean and count.
Pixel Inclusion Rule
Centroid rule (default): a cell is in the polygon if its centre is inside. All-touched rule: a cell is in the polygon if any part of it intersects the polygon. The all-touched rule helps for very small polygons that may not contain any cell centre.
Categorical vs Continuous
For categorical rasters (land cover, classification), the meaningful statistics are majority, minority and per-class proportions. For continuous rasters use mean, median and standard deviation.
Per-Class Output
For categorical rasters, the tool can produce one output column per class showing the proportion or count of cells of that class within each polygon.
Output Format
The enriched polygon layer is exported as GeoJSON, Shapefile, GeoPackage or CSV (attributes only).
Practical Applications
Watershed-Level Mean Elevation and Slope
A hydrologist computes mean elevation and mean slope for every watershed in a region using a DEM and a Slope/Aspect Calculator output. The resulting watershed table feeds runoff models and flood frequency analysis.
Field-Level NDVI Per Crop Block
A precision-agriculture analyst summarises Sentinel-2 NDVI within each field boundary polygon. The output is a per-field NDVI mean, standard deviation and count, which the farm manager uses to identify under-performing fields and target inputs.
Population Within Census Tracts
A demographer overlays a high-resolution population raster (WorldPop, GHSL) on census tract polygons and computes total population per tract via the sum statistic.
Land Cover Composition Per Park
A protected-area manager summarises a national land cover raster within each park boundary and computes the percentage of each cover class per park, tracking forest, grassland, water and urban over time.
Mean Annual Rainfall per Catchment
A climate scientist takes a gridded rainfall raster and a set of river catchment polygons and computes mean annual rainfall per catchment. The output drives water-balance models for hydropower planning.
Flood Depth Per Building Footprint
A disaster response analyst overlays a flood depth raster on building footprint polygons and computes the maximum flood depth touching each building, prioritising rescue and damage assessment.
Solar Potential Per Roof
A renewable energy consultant overlays a solar irradiance raster on rooftop polygons (from OpenStreetMap or building footprints) and computes mean annual irradiance per roof to estimate PV yield.
Burn Severity Per Fire Perimeter
After a wildfire, an analyst computes mean and majority dNBR severity within each fire perimeter polygon to report the area affected at each severity level.
Step-by-Step Workflow in gis.tools
- Open the Zonal Statistics page on gis.tools.
- Drag a raster GeoTIFF into the raster slot. The file is decoded with
geotiff.js. - Drag a polygon vector layer (GeoJSON, KML, Shapefile, GPKG) into the polygon slot.
- The tool checks CRS compatibility and reprojects the polygons to the raster CRS if needed.
- Choose the statistics to compute (mean, count, sum, min, max, std, median, majority, etc.).
- Choose the pixel inclusion rule: centroid or all-touched.
- Click Compute. The tool iterates over each polygon, extracts the relevant cells and aggregates the values.
- Preview the results in the polygon layer's attribute table or as a thematic map styled by one of the new statistics columns using Graduated Styling.
- Export the enriched polygon layer or the attributes-only CSV for downstream reporting.
Worked Example: Mean NDVI Per Field in an Iowa Farm
You have a Sentinel-2 NDVI raster covering an Iowa farm and a GeoJSON layer of 24 field boundary polygons. You drop both files into Zonal Statistics. The tool detects both layers in EPSG:32615 and runs without reprojection. You select mean, std, min, max and count. Click Compute. After about 2 seconds you have an enriched polygon layer where each field carries the four NDVI statistics. Field 14 shows mean NDVI 0.55 with high standard deviation 0.18, while Field 17 shows mean 0.85 with standard deviation 0.04. You suspect Field 14 has irrigation issues β the high variability suggests patchy crop performance. You style the layer by mean NDVI using Graduated Styling, confirming Field 14 stands out, and you export the attribute table to CSV for the farm manager.
Common Pitfalls and Gotchas
- CRS mismatch between raster and polygons silently produces wrong statistics. Always confirm both layers share a CRS.
- Very small polygons (smaller than one cell) may contain zero cells under the centroid rule and produce null statistics; switch to all-touched.
- Overlapping polygons each get their own statistics; cells in the overlap area count toward both.
- The MAUP (Modifiable Areal Unit Problem) means the statistics depend on the polygon boundaries β different boundary choices produce different conclusions.
- For categorical rasters, the mean is meaningless. Use majority or per-class proportions instead.
- Edge pixels with mixed inside/outside ground can bias mean values; consider buffering polygons inward for high-precision statistics.
- Forgetting to handle nodata: nodata cells are excluded from the statistic but are not counted in
count. - Floating-point sums of millions of cells can lose precision; use Kahan summation or compute means with Welford's algorithm.
Tips for Best Results
- For fields with few cells, use all-touched inclusion to avoid empty statistics.
- For continuous rasters, always report both mean and standard deviation β the spread matters.
- For categorical rasters, report per-class proportions, not just majority.
- Use the Clip Raster by Polygon tool first to crop the raster to the AOI bounding box and speed up the computation.
- Validate against a hand-computed check polygon before trusting batch results.
- Reproject the raster to a metric projected CRS so cell sizes are uniform and area-weighted statistics make sense.
- Save the original polygon layer separately so you can re-run with different statistics without re-computing.
- Use Graduated Styling to immediately visualise the new statistics on the polygon layer.
Comparison with Other GIS Approaches
QGIS provides the Zonal Statistics tool in the Processing Toolbox under Raster Analysis. ArcGIS Spatial Analyst's Zonal Statistics as Table is the canonical equivalent. GDAL has gdal_rasterize followed by gdal_calc.py workflows; Python with rasterstats offers a clean API. The Zonal Statistics tool on gis.tools mirrors all of these in a no-install browser environment with first-class GeoJSON output. The main trade-off is that the entire raster and polygon set must fit in browser memory; very large datasets are still better suited to a server-side pipeline.
Performance Considerations
Per polygon, the cost is dominated by the bounding-box crop and the point-in-polygon tests. For p polygons each containing n cells the total work is roughly O(p * n) for the cell tests plus O(p * v) for vertex traversal where v is the average polygon vertex count. A 4000x4000 raster with 100 polygons takes a few seconds. For large rasters or many polygons, clip the raster to the aggregate AOI first with Clip Raster by Polygon.
Data Privacy and Browser-Based Processing
The raster and polygon files are read with the File API and processed entirely in your browser tab. No data is uploaded; the resulting statistics live only in the page state until you export. This is essential for sensitive land-cover datasets, proprietary commercial imagery, classified terrain models and any workflow with strict data residency rules.
Related GIS Concepts
Modifiable Areal Unit Problem (MAUP): Statistics computed at one polygon size may differ from those at another. Always document zone definitions.
Centroid Rule vs All Touched: Two ways to decide whether a partially overlapping cell belongs to a zone.
Area-Weighted Statistics: Some applications need cells weighted by their fractional overlap with the polygon, not a binary include/exclude. Advanced zonal statistics tools offer this.
Tabular Output: Some workflows want only the statistics table without the geometry; the tool exports either.
Histogram Per Zone: A more detailed output that records the full distribution of cell values within each polygon.
Frequently Asked Questions
Can I compute zonal statistics on a categorical raster?
Yes β use majority, minority, unique value count and per-class proportions instead of mean and standard deviation.
What happens if my polygon is smaller than a cell?
Under the centroid rule it may contain zero cells. Switch to the all-touched rule to capture the cell that contains the polygon.
Do overlapping polygons count cells twice?
Yes β each polygon gets its own statistics computed independently. Cells in the overlap contribute to both.
Can I compute multiple statistics in one pass?
Yes β select all the statistics you want before clicking Compute. The tool produces one column per statistic.
Why are some polygons missing statistics?
Either the polygon contains no valid cells (small polygon or all-nodata area) or the geometry is invalid. Check with the GeoJSON Validator & Fixer.
Does the tool handle multi-band rasters?
Yes β statistics are computed per band, with one set of columns per band.
Related Tools on gis.tools
Related Tools
View All ToolsGeoTIFF Viewer
View GeoTIFF bands with nodata handling and min/max stretch
Raster ToolsSlope/Aspect Calculator
Calculate slope and aspect from elevation data
Raster ToolsRaster Mosaic Preview
Preview multiple raster tiles as a single view
Raster ToolsRaster to Points
Sample raster values to a point grid
Raster ToolsRaster Resampler
Resample raster with nearest neighbor or bilinear interpolation
Raster ToolsNDVI Calculator
Calculate vegetation index from multispectral imagery
Raster Tools100% client-side processing - your data stays private and never leaves your device