geopandas
Geopandas uses shapely geometry objects and it can do plot, spatial join
This is an example of loading shapely polygons from a numpy array.
The shapely polygons are further loaded to pandas and geopandas.
geopandas then plots the shape.
import pandas as pd
from shapely.geometry import Polygon
import matplotlib.pyplot as plt
#polygon coordinates x1,y1, x2,y2, ...xn,yn, x1,y1
polygons=[
[[0,0], [10,0], [10,10], [0,10], [0,0]],
[[5,5], [20,5], [20,20], [5,20], [5,5]],
]
#convert from array to polygon objects
polygons = [Polygon(i) for i in polygons]
#load polybon objects to pandas
df_polygons = pd.DataFrame(polygons, columns=['Poly'])
#convert pandas dataframe to geopandas dataframe and indicate the column of geometry object
gdf_polygons = gp.GeoDataFrame(
df_polygons,
geometry='Poly',
crs='epsg:28355',
)
#simply plot all the geometry objects
gdf_polygons.plot(figsize=(5,5))
#can also plot to an matplotlib ax
#so as to combine with other plots
fig, ax = plt.subplots(1,1,figsize=(5,5))
gdf_polygons.plot(ax=ax)
plt.show()
The shapley geometry objects can be loaded from the string format directly as well
just use the wkt functions to intantiate the objects from string
the geopandas plot function can take matplotlib ax as a paramter so can overlap the plot with other plots
import pandas as pd
from shapely.geometry import Polygon, LineString, Point
import shapely.wkt as wkt
import matplotlib.pyplot as plt
#geometry objects in string format
geometry=[
'Polygon((0 0, 10 0, 10 10, 0 10, 0 0))',
'Polygon((5 5, 20 5, 20 20, 5 20, 5 5))',
'LineString(0 20, 20 0)',
'Point(30 30)',
]
#load polybon objects to pandas
df = pd.DataFrame(geometry, columns=['geom'])
df['geom'] = df['geom'].apply(lambda x: wkt.loads(x))
#convert pandas dataframe to geopandas dataframe and indicate the column of geometry object
gdf = gp.GeoDataFrame(
df,
geometry='geom',
crs='epsg:28355',
)
#simply plot all the geometry objects
gdf.plot(figsize=(5,5))
Finally spatial join (sjoin) is handy to check if geometry objects intersect/contain with others.
The join type can be inner, left, right
import pandas as pd
from shapely.geometry import Polygon, LineString, Point
import shapely.wkt as wkt
import matplotlib.pyplot as plt
#geometry objects in string format
geometry=[
'Polygon((0 0, 10 0, 10 10, 0 10, 0 0))',
'Polygon((5 5, 20 5, 20 20, 5 20, 5 5))',
]
#load polybon objects to pandas
df = pd.DataFrame(geometry, columns=['geom'])
df['geom'] = df['geom'].apply(lambda x: wkt.loads(x))
#convert pandas dataframe to geopandas dataframe and indicate the column of geometry object
gdf = gp.GeoDataFrame(
df,
geometry='geom',
crs='epsg:28355',
)
gdf1 = gdf.loc[[True, False]]
gdf2 = gdf.loc[[False, True]]
gdf_joined = gp.sjoin(
gdf1,
gdf2,
how='inner',
op='intersects', #{‘intersects’, ‘contains’, ‘within’}
)
fig, ax = plt.subplots(1,1,figsize=(5,5))
gdf1.plot(ax=ax, color='blue')
gdf2.plot(ax=ax, color='green')
plt.show()
gdf_joined.plot()