3

I have a polygon that is formed using Quick OSM.

enter image description here

After that, I add an area calculation field to it, automatically using the QGIS tools.

enter image description here

How can I use PyQGIS to get the sum of the areas of the selected parts of the polygon multiplied by 5 and display the answer in the Python Console?

3
  • 2
    You could do all that using QGIS expressions, without Python. The solution must be using Python?
    – Babel
    Commented Dec 26, 2023 at 16:18
  • yes, it is on python Commented Dec 26, 2023 at 16:29
  • 2
    Please edit the question to clarify that you need a Python solution and add a code attempt. As it's currently written ("or in some other way") it suggests that you are open for other solutions as well. Maybe give a reason then why you need a Python version for a typical "non-Python" workflow.
    – winnewoerp
    Commented Dec 26, 2023 at 16:56

2 Answers 2

3

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:

1
  • thank you for your answer, it helped me, and also a lot of different solutions, very cool Commented Dec 26, 2023 at 19:15
1

here is the python script based on the data in the column Area from the attribute table

# Access the active layer (which should be your polygon layer)
layer = iface.activeLayer()
# Check if the layer is indeed a vector layer
if not layer or not isinstance(layer, QgsVectorLayer):
    print("Active layer is not a vector layer.")
else:
    # Initialize a variable to hold the sum of the areas
    sum_of_areas = 0
    
    # Loop through each selected feature in the layer
    for feature in layer.selectedFeatures():
        # Assuming the field that stores the area is named 'Area'
        # Make sure to replace 'Area' with the actual name of your area field
        area = feature['Area']
        
        # Multiply the area by 5 and add to the total sum
        sum_of_areas += area * 5
    
    # Print the total sum in the Python Console
    print(f"The total sum of the selected areas multiplied by 5 is: {sum_of_areas}")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.