簡體   English   中英

python plot 多邊形中點的規則網格

[英]python plot a regular grid of points in a polygon

我想 plot 一個多邊形內的規則網格點。

將以下內容作為多邊形:

import geopandas as gpd
from shapely.geometry import Polygon

x = [0, 100, 150, 100, 50]
y = [0, 115, 200, 250, 50]

polygon_geom = Polygon(zip(x, y))
crs = 'epsg:27700'
polygon = gpd.GeoDataFrame(index=[0], crs=crs, geometry=[polygon_geom])   

使用這個范圍,我想在常規網格上 plot 點,這些點在 NS 和 EW 中的距離為 10。

那么它應該只是使用contains查詢將它們保留在多邊形內的問題。

我修改了您的點,因此通過刪除最后一組點使多邊形有效:

import geopandas as gpd
from shapely.geometry import Polygon

x = [0, 100, 150, 100]
y = [0, 115, 200, 250]

polygon_geom = Polygon(zip(x, y))
crs = 'epsg:27700'
polygon = gpd.GeoDataFrame(index=[0], crs=crs, geometry=[polygon_geom])

不確定您正在尋找的網格規范,但您可以按照以下方式做一些事情:

import numpy as np, pandas as pd, shapely.vectorized
import matplotlib.pyplot as plt

# define grid spec from min to max value with spacing of grid_res=10
grid_res = 10

# this isn't necessary in your case, but if your polygon had
# boundaries not falling on grid edges, you might want to ensure
# the grid started on specific cell boundaries or midpoints
minx = np.floor(polygon_geom.bounds[0] / grid_res) * grid_res
maxx = np.ceil(polygon_geom.bounds[2] / grid_res) * grid_res
miny = np.floor(polygon_geom.bounds[1] / grid_res) * grid_res
maxy = np.ceil(polygon_geom.bounds[3] / grid_res) * grid_res

minx, maxx, miny, maxy  # (0.0, 150.0, 0.0, 250.0)

# you can form the grid by setting up the coordinates and then filling
# the grid with numpy.meshgrid
x = np.arange(minx, maxx + grid_res / 2, grid_res)
y = np.arange(miny, maxy + grid_res / 2, grid_res)
XX, YY = np.meshgrid(x, y)

# use shapely.vectorized to find all points within the polygon
in_polygon = shapely.vectorized.contains(polygon_geom, XX, YY)

# filter the points and flatten them to 1D vectors
x_in_polygon = XX[in_polygon].ravel()
y_in_polygon = YY[in_polygon].ravel()

然后可以這樣繪制:

In [41]: fig, ax = plt.subplots()
    ...: polygon.plot(color='none', edgecolor='k', ax=ax)
    ...: ax.scatter(x_in_polygon, y_in_polygon, zorder=-1, s=0.4)

帶有黑色輪廓的多邊形圖形,規則網格上的點僅過濾為多邊形內的點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM