To sum up all features' areas can be done either via
the "FIELD_NAME"
field, that contains area values:
# imports
from qgis.core import QgsProject, QgsAggregateCalculator
# getting polygon layer by its name
layer = QgsProject.instance().mapLayersByName("YOUR_LAYER_NAME")[0]
# summing area of all features
area_total_sum = layer.aggregate(QgsAggregateCalculator.Sum, "FIELD_NAME")
print(area_total_sum) # (19594.140492000002, True)
or the $area
variable directly:
# imports
from qgis.core import QgsProject, QgsAggregateCalculator
# getting polygon layer by its name
layer = QgsProject.instance().mapLayersByName("YOUR_LAYER_NAME")[0]
# summing area of all features
area_total_sum = layer.aggregate(QgsAggregateCalculator.Sum, "$area")
print(area_total_sum) # (19594.140491519036, True)
Then if necessary proceed with area_total_sum[0] * 5
.
If one applies this expression area($geometry)
the result will be slightly different (19603.3203125, True)
. Therefore, pay attention to this thread: Calculating polygon areas in shapefile using QGIS.
To sum up only selected features' areas can be done either via:
the aggregate()
method of the QgsVectorLayer
class:
# imports
from qgis.core import QgsProject, QgsAggregateCalculator
# getting polygon layer by its name
layer = QgsProject.instance().mapLayersByName("YOUR_LAYER_NAME")[0]
# summing area of selected features
area_selected_sum = layer.aggregate(
aggregate=QgsAggregateCalculator.Sum,
fieldOrExpression="FIELD_NAME",
fids=layer.selectedFeatureIds()
)
print(area_selected_sum) # (1958.09388, True)
or the calculate()
method of the QgsAggregateCalculator
class:
# imports
from qgis.core import QgsProject, QgsAggregateCalculator
# getting polygon layer by its name
layer = QgsProject.instance().mapLayersByName("YOUR_LAYER_NAME")[0]
# constructing the aggregate calculator
agg_calc = QgsAggregateCalculator(layer)
# setting a filter for selected features only
agg_calc.setFidsFilter(layer.selectedFeatureIds())
# summing area of selected features
area_selected_sum = agg_calc.calculate(QgsAggregateCalculator.Sum, "FIELD_NAME")
print(area_selected_sum) # (1958.09388, True)
As was already previously shown, instead of the "FIELD_NAME"
one can also use either $area
or area($geometry)
.
Then if necessary proceed with area_selected_sum[0] * 5
.
References: