Points and lines

Shapely's Point and LineString, what distance means in a flat plane, and why a line's centroid is not the average of its vertices.

What you'll learn
  • Create Point and LineString objects and read their coordinates
  • Explain what Shapely's distance measures — and what it does not
  • Compute a LineString's length and centroid by hand

The notebook starts with three points:

from shapely.geometry import Point, LineString, Polygon

point1 = Point(2.2, 4.2)
point2 = Point(7.2, -25.1)
point3 = Point(9.26, -2.456)
point3D = Point(9.26, -2.456, 9.57)

A Point is just coordinates: point1.x, point1.y, and point1.coords for the sequence. A third coordinate is stored but ignored by every 2D calculation — area, length and distance all live in the \(xy\)-plane.

Distance is planar

point_dist = point1.distance(point2)   # 29.7236

This is the straight-line Euclidean distance \(\sqrt{(7.2 - 2.2)^2 + (-25.1 - 4.2)^2} = 29.72\). The notebook’s comment says “in decimal degrees”, which is true in a limited sense: if the coordinates are longitude and latitude, the result is in degrees too. But a degree is not a fixed length. A degree of latitude is about 111 km everywhere, while a degree of longitude shrinks with \(\cos(\text{latitude})\) — 111 km at the equator, 56 km at 60° N. Near the equator, as here, the number happens to work: 29.72° × 111.2 km ≈ 3,305 km, against a great-circle distance of 3,302 km. Further from the equator, the planar answer can be off by a factor of two. For real distances on the Earth, project the coordinates to a metric system first, or use a geodesic library such as pyproj.

LineString: length and centroid

line = LineString([point1, point2, point3])
line.length       # 52.461
line.centroid     # POINT (6.230 -11.892)

The length is the sum of the segment lengths: \(29.72 + 22.74 = 52.46\).

The centroid is where a uniform wire bent into this shape would balance. Each segment pulls with a weight equal to its length, at its midpoint \(\mathbf{m}_i\):

\[\mathbf{c} = \frac{\sum_i L_i\,\mathbf{m}_i}{\sum_i L_i}\]

The plain average of the three vertices is \((6.22, -7.79)\) — four units away. The first segment is the longer one, so it drags the centroid towards its own midpoint.

The notebook's line with its third vertex circling. Blue discs are segment midpoints, sized by length; green is line.centroid, orange is the vertex average. They coincide only when the segments are equally long.

Try it yourself. Build LineString([(0, 0), (10, 0), (10, 1)]) and predict its centroid before printing it. Then add the point (10, 0.5) in the middle of the last segment. The vertex average moves; does line.centroid? Explain with the formula above.

View source on GitHub →