QGIS – How to Count Points in Percentage Within an Extension Defined by Coordinates Pairs

labelingqgisqgis-expressionselect-by-location

Starting from a points geometry layer, my goal is to count points in percentage that are within an extension defined by two pairs of coordinates corresponding to the corners:

The initial situation is as shown in the following screen shot:

enter image description here

The goal would be to get to labeling the percentage of points that are within the extension and the percentage of points that are outside the extent. The idea behind this issue need is to use a labeling expression that avoids using a physical layer of polygons. I add a recreation of what I am looking for:

enter image description here

Solution implementation:

I have tried the eurojam user solution and the correction from Xeppit user.

As you can see I have a layer of 10 points. 5 points are within the rectangle extension and 5 points are outside rectangle. Therefore the result should be 50%.

The rectangle has the following coordinates:

'lowerleft': '-0.00,-4.49'

'upperright': '5.40,4.45'

And the expression I use is:

round(with_variable(
'lowerleft',
'-0.00,-4.49',
with_variable(
'upperright',
'5.40,4.45',
with_variable('rect',
      make_rectangle_3points( 
         make_point(to_real(string_to_array(@lowerleft,',')[0]),to_real(string_to_array(@lowerleft,',')[1])),
         make_point(to_real(string_to_array(@upperright,',')[0]),to_real(string_to_array(@lowerleft,',')[1])),
         make_point(to_real(string_to_array(@upperright,',')[1]),to_real(string_to_array(@upperright,',')[1]))),
      aggregate(layer:='points',
         aggregate:='count',
         expression:=$id,
         filter:=intersects($geometry, @rect)))))
    / count($id) * 100,2) || ' %'

enter image description here

Best Answer

There is a mistake in make_rectangle_3points geometry:

enter image description here

It should be

 make_rectangle_3points( 
         make_point(to_real(string_to_array(@lowerleft,',')[0]),to_real(string_to_array(@lowerleft,',')[1])),
         make_point(to_real(string_to_array(@upperright,',')[0]),to_real(string_to_array(@lowerleft,',')[1])),
         make_point(to_real(string_to_array(@upperright,',')[1]),to_real(string_to_array(@upperright,',')[1])

--> Last line !

enter image description here

Check your rect geometry with geometry generator in symbology of a seperate layer that you can see the selecting rectangle and adapt it to your needs.