rafine
rafine

Reputation: 471

centroids within the polygon or line

in geopandas I use this code to create centroid parameter from geometric parameter.

df["center"]=df.centroid

I want to force the calculation of the centroids to be within the polygon. here i found somthing in R. can I do it in python?

Calculate Centroid WITHIN / INSIDE a SpatialPolygon

Upvotes: 0

Views: 3026

Answers (1)

swatchai
swatchai

Reputation: 18772

To get the representative points that always fall within their corresponding polygons can be done in geopandas with the function called representative_point(). Here is a demo code that creates and plots the polygons and their rep. points.

import pandas as pd
import geopandas as gpd
from shapely import wkt
from shapely.geometry import Point, Polygon
from shapely.wkt import loads

#Create some test data
d = {'col1': [1,2],
     'wkt': [
         'POLYGON ((700000 5500000, 700000 5600000, 800000 5600000, 800000 5500000, 700000 5500000))',
        """POLYGON ((1441727.5096940901130438 6550163.0046194596216083, 
                     1150685.2609429201111197 6669225.7427449300885201, 
                     975398.4520359700545669 6603079.7771196700632572, 
                     866257.6087542800232768 6401334.5819626096636057, 
                     836491.9242229099618271 6106985.0349301798269153, 
                     972091.1537546999752522 5835786.5758665995672345, 
                     1547561.0546945100650191 5782869.8033663900569081, 
                     1408654.5268814601004124 5600968.3978968998417258, 
                     720736.4843787000281736 5663807.0652409195899963, 
                     598366.4479719599476084 6001151.4899297598749399, 
                     654590.5187534400029108 6341803.2128998702391982, 
                     869564.9070355399744585 6784981.1825891500338912, 
                     1451649.4045378800947219 6788288.4808704098686576, 
                     1441727.5096940901130438 6550163.0046194596216083))"""

     ]
    }
df = pd.DataFrame( data=d )
gdf = gpd.GeoDataFrame(df, \
                   crs={'init': 'epsg:3857'}, \
                   geometry=[loads(pgon) for pgon in df.wkt])
gdf4326 = gdf.to_crs(4326)  #coordinates in plain degrees

# create 2nd geometry column, for representative points
gdf4326["geometry2"] = gdf4326.representative_point()

# plot all layers of geometries
# 1. the polygons in gray
ax1 = gdf4326.plot(color="gray", alpha=0.5)
# 2. the representative points as red dots
gdf4326.set_geometry('geometry2').plot(zorder=10, color='red', ax=ax1)

If centroid is chosen instead of representative_point, one of the red dots will fall outside it's corresponding polygon.

poly_pnts

Upvotes: 4

Related Questions