I'm trying to create a timeseries of raster data (one layer per year) by polygon (Administrative regions). Is there any way in QGIS to perform Zonal Statistics for multiple years (without having to perform the zonal statistics function each time)? Or something along the lines of the Point Sampling tool but for polygons?
-
Have you already tried to call the geoprocessing function from inside a for loop over years in Python console?– DetlevJun 10, 2015 at 17:28
2 Answers
I have something fairly close, although it only currently works for average and rejects max and min.
- Save all your raster layers in one folder with the same extension (e.g. .tif)
- Load shapefile (polygons) into QGIS
Open Python (Plugins > Python console) and run the following
import glob, os, qgis.analysis vectorlayer = qgis.utils.iface.mapCanvas().currentLayer() rasterfolder = 'C:/Users/…/Folder/' os.chdir(rasterfolder) for lyr in glob.glob("*.tif"): qgis.analysis.QgsZonalStatistics(vectorlayer, lyr, attributePrefix=lyr, rasterBand=1).calculateStatistics(None)
Using the vector layer loaded in QGIS was an easy way to append the results to the attribute table. The code to loop through rasters in a folder was from here.
If there is a way to specify the statistic using QgsZonalStatistics.Mean
that would be helpful to know.
For mean only use
os.chdir(rasterfolder)
for lyr in glob.glob("*.tif") :
qgis.analysis.QgsZonalStatistics(vector, lyr, attributePrefix=lyr, rasterBand=1, stats=QgsZonalStatistics.Statistics(QgsZonalStatistics.Mean)).calculateStatistics(None)
-
1You should provide a little more text to say how this answers, or part answers the question– nmtokenJan 2, 2018 at 12:21