I added some algorithms to the ProcessX Plugin in the past for this usecase. You can use one of the following processing tools. Both accept points, lines and polygons for both inputs. You can also choose between different geometric predicates such as contains, within, intersects, etc.
- Count Features in Features with Condition (you do not need to use an attribute condition)
This Algorithm counts
features in features with a given optional attribute condition. To count singlepoints in
polygons use "Count Points in Polygons with Condition" algorithm instead - it
is a lot faster for this case
- Count Features in Features by Category
This Algorithm counts features
in features (both can be Points, Lines or Polygons of any type) by a
given category, evaluated either via an expression or a field. If it
does not find a match, it adds a 0 as count. You can also choose one
or multiple geometric predicate(s) on which features you want to count
and set whether only at least one predicate must match or all of them.
Additionally you may choose whether a feature should be counted only
once or multiple times. You can set up the structure of the output
layer yourself, the options are: Create a feature for each category:
This creates a new feature for every source feature and every possible
category. You will get n_source_features * n_categories =
n_output_features with two fields; One indicating the name of the
category and one having the count of this category. Create a field
for each category: This creates one single feature for every source
feature with one field for each category containing the count of this
category for this feature. Warning: If the number of different
categories exceed the limit of maximum fields possible, this option
can crash QGIS (especially when opening the attribute table). Create
a dictionary/map for all categories: This creates one single feature
for every source feature with one field containing the results for
this feature. The result will be a string in form of a Python
dictionary with the category names as keys and the category counts as
values, like {'cat_a':0,'cat_b':13,'cat_c':7}. Warning: If the length
of the sum of all different category names exceeds the maximum string
length, this option can crash QGIS (especially when opening the
attribute table). With both options you are save if you do not have
weird characters in the category names, a lot of different categories
and the category names are quite short. If you are unsure, just use
Create a feature for each category.