Convert Figma logo to code with AI

shapely logoshapely

Manipulation and analysis of geometric objects

3,831
565
3,831
284

Top Related Projects

Python tools for geographic data

1,040

Python interface to PROJ (cartographic projections and coordinate transformations library)

1,145

Fiona reads and writes geographic data files

1,310

PySAL: Python Spatial Analysis Library Meta-Package

1,091

This library reads and writes ESRI Shapefiles in pure Python.

Quick Overview

Shapely is a Python package for manipulation and analysis of geometric objects in the Cartesian plane. It is based on the GEOS library and provides a rich set of geometric operations and predicates, making it a powerful tool for working with 2D geometries in various fields such as GIS, data science, and computational geometry.

Pros

  • Extensive set of geometric operations and predicates
  • Efficient implementation based on the well-established GEOS library
  • Seamless integration with other geospatial libraries in the Python ecosystem
  • Clear and comprehensive documentation

Cons

  • Limited to 2D geometries (no 3D support)
  • Performance can be slower compared to some specialized libraries for specific operations
  • Steep learning curve for users new to computational geometry concepts

Code Examples

  1. Creating and manipulating geometries:
from shapely.geometry import Point, LineString, Polygon

# Create a point
point = Point(0, 0)

# Create a line
line = LineString([(0, 0), (1, 1), (2, 2)])

# Create a polygon
polygon = Polygon([(0, 0), (1, 1), (1, 0)])

# Check if the point is within the polygon
is_within = point.within(polygon)
print(f"Is the point within the polygon? {is_within}")
  1. Performing geometric operations:
from shapely.geometry import Point
from shapely.ops import unary_union

# Create multiple points
points = [Point(0, 0), Point(1, 1), Point(2, 2)]

# Create a buffer around each point
buffered_points = [p.buffer(0.5) for p in points]

# Merge the buffered areas
merged_area = unary_union(buffered_points)

print(f"Area of merged buffers: {merged_area.area}")
  1. Working with GeoJSON:
from shapely.geometry import shape
import json

# GeoJSON representation of a polygon
geojson = {
    "type": "Polygon",
    "coordinates": [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]
}

# Convert GeoJSON to Shapely geometry
polygon = shape(geojson)

# Perform operations on the geometry
centroid = polygon.centroid
print(f"Centroid of the polygon: {centroid.x}, {centroid.y}")

Getting Started

To get started with Shapely, follow these steps:

  1. Install Shapely using pip:

    pip install shapely
    
  2. Import the necessary modules in your Python script:

    from shapely.geometry import Point, LineString, Polygon
    
  3. Start creating and manipulating geometries:

    point = Point(0, 0)
    line = LineString([(0, 0), (1, 1)])
    polygon = Polygon([(0, 0), (1, 1), (1, 0)])
    
    # Perform operations
    buffer = point.buffer(1)
    intersection = line.intersection(polygon)
    

For more detailed information and advanced usage, refer to the official Shapely documentation.

Competitor Comparisons

Python tools for geographic data

Pros of GeoPandas

  • Integrates spatial operations with pandas DataFrames for easier data manipulation
  • Provides high-level interface for complex geospatial operations
  • Supports reading/writing various geospatial file formats out-of-the-box

Cons of GeoPandas

  • Heavier dependency footprint due to pandas and other libraries
  • Slower performance for basic geometric operations
  • Steeper learning curve for users unfamiliar with pandas

Code Comparison

Shapely:

from shapely.geometry import Point, Polygon

point = Point(0, 0)
polygon = Polygon([(0, 0), (1, 1), (1, 0)])
print(polygon.contains(point))

GeoPandas:

import geopandas as gpd
from shapely.geometry import Point, Polygon

gdf = gpd.GeoDataFrame({'geometry': [Point(0, 0), Polygon([(0, 0), (1, 1), (1, 0)])]})
print(gdf.iloc[1].geometry.contains(gdf.iloc[0].geometry))
1,040

Python interface to PROJ (cartographic projections and coordinate transformations library)

Pros of pyproj

  • Specializes in coordinate system transformations and geodetic calculations
  • Provides access to the PROJ library, offering a wide range of projection methods
  • Supports both forward and inverse projections

Cons of pyproj

  • Steeper learning curve for users unfamiliar with geodetic concepts
  • Limited functionality for geometric operations compared to Shapely
  • May require additional libraries for complex spatial analysis tasks

Code Comparison

pyproj example:

from pyproj import Transformer
transformer = Transformer.from_crs("EPSG:4326", "EPSG:3857")
x, y = transformer.transform(51.5074, -0.1278)

Shapely example:

from shapely.geometry import Point
point = Point(-0.1278, 51.5074)
buffer = point.buffer(1000)

Summary

pyproj excels in coordinate transformations and geodetic calculations, making it ideal for projects requiring precise geographic conversions. Shapely, on the other hand, focuses on geometric operations and spatial analysis, offering a more intuitive interface for working with shapes and polygons. While pyproj provides powerful projection capabilities, Shapely is better suited for general-purpose spatial data manipulation. The choice between the two depends on the specific requirements of your geospatial project.

1,145

Fiona reads and writes geographic data files

Pros of Fiona

  • Focuses on reading and writing geospatial data files
  • Supports a wide range of vector data formats (e.g., Shapefile, GeoJSON, GeoPackage)
  • Provides a simpler, more Pythonic API for working with geospatial data

Cons of Fiona

  • Limited geometric operations compared to Shapely
  • Slower performance for certain operations
  • Steeper learning curve for users familiar with OGR

Code Comparison

Fiona:

import fiona

with fiona.open('data.shp', 'r') as source:
    for feature in source:
        print(feature['geometry'])

Shapely:

from shapely.geometry import shape
import json

with open('data.geojson', 'r') as f:
    geom = shape(json.load(f)['geometry'])
print(geom)

Summary

Fiona excels at reading and writing geospatial data files, offering support for various formats and a more Pythonic API. However, it has limited geometric operations compared to Shapely. Shapely, on the other hand, focuses on manipulating and analyzing geometric objects, providing a wide range of operations but lacking direct file I/O capabilities. The choice between the two depends on the specific requirements of your geospatial project.

1,310

PySAL: Python Spatial Analysis Library Meta-Package

Pros of PySAL

  • Comprehensive spatial analysis toolkit with advanced statistical methods
  • Modular architecture allowing for flexible use of components
  • Strong focus on spatial econometrics and geospatial data science

Cons of PySAL

  • Steeper learning curve due to its extensive functionality
  • May be overkill for simple geometric operations
  • Less focused on basic geometry manipulation compared to Shapely

Code Comparison

Shapely example:

from shapely.geometry import Point, Polygon

point = Point(0, 0)
polygon = Polygon([(0, 0), (1, 1), (1, 0)])
print(polygon.contains(point))

PySAL example:

from pysal.lib import weights
from pysal.explore import esda

w = weights.KNN.from_dataframe(df, k=5)
moran = esda.Moran(df['variable'], w)
print(moran.I)

PySAL offers more complex spatial analysis capabilities, while Shapely focuses on simpler geometric operations. Shapely is generally easier to use for basic tasks, but PySAL provides a wider range of advanced spatial analysis tools and statistical methods.

1,091

This library reads and writes ESRI Shapefiles in pure Python.

Pros of pyshp

  • Lightweight and focused specifically on reading/writing ESRI Shapefile format
  • Simple API for basic shapefile operations
  • Pure Python implementation, no external dependencies required

Cons of pyshp

  • Limited functionality compared to Shapely's broader geospatial capabilities
  • Lacks advanced geometric operations and analysis tools
  • Not as actively maintained or widely used in the geospatial community

Code Comparison

pyshp:

import shapefile

# Read a shapefile
sf = shapefile.Reader("shapefile.shp")

# Get the first shape
shape = sf.shape(0)

# Access coordinates
points = shape.points

Shapely:

from shapely.geometry import shape
import fiona

# Read a shapefile using Fiona
with fiona.open("shapefile.shp") as src:
    geom = shape(src[0]['geometry'])

# Access coordinates
points = list(geom.exterior.coords)

Both libraries can read shapefiles, but Shapely offers more advanced geometric operations and analysis tools. pyshp is more focused on basic shapefile handling, while Shapely provides a broader range of geospatial functionality. Shapely often requires additional libraries like Fiona for file I/O, whereas pyshp is self-contained for shapefile operations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

======= Shapely

.. Documentation at RTD — https://readthedocs.org

.. image:: https://readthedocs.org/projects/shapely/badge/?version=stable :alt: Documentation Status :target: https://shapely.readthedocs.io/en/stable/

.. Github Actions status — https://github.com/shapely/shapely/actions

.. |github-actions| image:: https://github.com/shapely/shapely/workflows/Tests/badge.svg?branch=main :alt: Github Actions status :target: https://github.com/shapely/shapely/actions?query=branch%3Amain

.. Travis CI status -- https://travis-ci.com

.. image:: https://travis-ci.com/shapely/shapely.svg?branch=main :alt: Travis CI status :target: https://travis-ci.com/github/shapely/shapely

.. PyPI

.. image:: https://img.shields.io/pypi/v/shapely.svg :alt: PyPI :target: https://pypi.org/project/shapely/

.. Anaconda

.. image:: https://img.shields.io/conda/vn/conda-forge/shapely :alt: Anaconda :target: https://anaconda.org/conda-forge/shapely

.. Coverage

.. |coveralls| image:: https://coveralls.io/repos/github/shapely/shapely/badge.svg?branch=main :target: https://coveralls.io/github/shapely/shapely?branch=main

.. Zenodo

.. .. image:: https://zenodo.org/badge/191151963.svg .. :alt: Zenodo .. :target: https://zenodo.org/badge/latestdoi/191151963

Manipulation and analysis of geometric objects in the Cartesian plane.

.. image:: https://c2.staticflickr.com/6/5560/31301790086_b3472ea4e9_c.jpg :width: 800 :height: 378

Shapely is a BSD-licensed Python package for manipulation and analysis of planar geometric objects. It is using the widely deployed open-source geometry library GEOS <https://libgeos.org/>__ (the engine of PostGIS <https://postgis.net/>, and a port of JTS <https://locationtech.github.io/jts/>). Shapely wraps GEOS geometries and operations to provide both a feature rich Geometry interface for singular (scalar) geometries and higher-performance NumPy ufuncs for operations using arrays of geometries. Shapely is not primarily focused on data serialization formats or coordinate systems, but can be readily integrated with packages that are.

What is a ufunc?

A universal function (or ufunc for short) is a function that operates on n-dimensional arrays on an element-by-element fashion and supports array broadcasting. The underlying for loops are implemented in C to reduce the overhead of the Python interpreter.

Multithreading

Shapely functions generally support multithreading by releasing the Global Interpreter Lock (GIL) during execution. Normally in Python, the GIL prevents multiple threads from computing at the same time. Shapely functions internally release this constraint so that the heavy lifting done by GEOS can be done in parallel, from a single Python process.

Usage

Here is the canonical example of building an approximately circular patch by buffering a point, using the scalar Geometry interface:

.. code-block:: pycon

>>> from shapely import Point
>>> patch = Point(0.0, 0.0).buffer(10.0)
>>> patch
<POLYGON ((10 0, 9.952 -0.98, 9.808 -1.951, 9.569 -2.903, 9.239 -3.827, 8.81...>
>>> patch.area
313.6548490545941

Using the vectorized ufunc interface (instead of using a manual for loop), compare an array of points with a polygon:

.. code:: python

>>> import shapely
>>> import numpy as np
>>> geoms = np.array([Point(0, 0), Point(1, 1), Point(2, 2)])
>>> polygon = shapely.box(0, 0, 2, 2)

>>> shapely.contains(polygon, geoms)
array([False,  True, False])

See the documentation for more examples and guidance: https://shapely.readthedocs.io

Requirements

Shapely 2.1 requires

  • Python >=3.9
  • GEOS >=3.9
  • NumPy >=1.20

Installing Shapely

We recommend installing Shapely using one of the available built distributions, for example using pip or conda:

.. code-block:: console

$ pip install shapely
# or using conda
$ conda install shapely --channel conda-forge

See the installation documentation <https://shapely.readthedocs.io/en/latest/installation.html>__ for more details and advanced installation instructions.

Integration

Shapely does not read or write data files, but it can serialize and deserialize using several well known formats and protocols. The shapely.wkb and shapely.wkt modules provide dumpers and loaders inspired by Python's pickle module.

.. code-block:: pycon

>>> from shapely.wkt import dumps, loads
>>> dumps(loads('POINT (0 0)'))
'POINT (0.0000000000000000 0.0000000000000000)'

Shapely can also integrate with other Python GIS packages using GeoJSON-like dicts.

.. code-block:: pycon

>>> import json
>>> from shapely.geometry import mapping, shape
>>> s = shape(json.loads('{"type": "Point", "coordinates": [0.0, 0.0]}'))
>>> s
<POINT (0 0)>
>>> print(json.dumps(mapping(s)))
{"type": "Point", "coordinates": [0.0, 0.0]}

Support

Questions about using Shapely may be asked on the GIS StackExchange <https://gis.stackexchange.com/questions/tagged/shapely>__ using the "shapely" tag.

Bugs may be reported at https://github.com/shapely/shapely/issues.

Copyright & License

Shapely is licensed under BSD 3-Clause license. GEOS is available under the terms of GNU Lesser General Public License (LGPL) 2.1 at https://libgeos.org.