5

I have done the following in QGIS: I used the integrated k-means clustering tool to cluster around 160k data points into 50 clusters. Using the mean coordinate tool (Vector analysis > Mean coordinates) I found the center point of each cluster.

I now want to find the overall mean distance from all points in a respective cluster to the center point of that cluster; so in the end, I want 50 mean distances, one for each cluster. I currently have these two-point sets (clusters and center points) saved as two separate shapefiles.

How do I do this?

1

2 Answers 2

5

On the layer with the center point, you can use QGIS expressions. Get an array of the points from the same cluster using array_foreach and then for each of these points create create a line to the center and get it's length. You get an array of lengths. With array_mean, calculate the mean. This is how the expression looks like:

array_mean (
    array_foreach (
        overlay_nearest('points', $geometry, limit:=-1),
        length (
            make_line (
                $geometry,
                @element
            )
        )
    )
)

Based on the data you have and how it is structured, you have to include a condition so that only points belonging to the same center are considered.

From the red center point, the expression generates a line to each of the white dots from the points layer, measures the length and gets the mean. The lines itself that you see here are generated with an expression based on this one with Geometry generator, see on the right side:

enter image description here

4

Assuming that you've got two layers:

  1. Clusters, that holds all your points, each one identified as belonging to a specific cluster by means of an attribute named cluster_id;
  2. Center_points with as many points as clusters you've created, and each of them representing the mean coordinates of the cluster, again identified by means of an attribute named "cluster_id".

You can create a "Virtual layer" through Layer > Create Layer > Create Virtual Layer with the following code:

SELECT
    p.cluster_id,
    avg(st_distance(c.geometry, p.geometry))
FROM
    Center_points p,
    Clusters c
WHERE
    p.cluster_id = c.cluster_id
GROUP BY
    p.cluster_id;

Anyway, beware the CRS of both layers, which should be the same and with projected coordinates, so the rendered results are in meters.

0

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.