end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

shapely for python で、穴あきpolygonを作成し、matplotlib で描画

pgRouting を使用した 幾何学図形に対する経路探索 - end0tknr's kipple - web写経開発

以前、上記のentry で、pgRouting (postgis) を使用し、 穴あきpolygonを描画しましたが、今回の場合は、pythonで。

# coding: utf-8

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path        import Path
from matplotlib.patches     import PathPatch
from matplotlib.collections import PatchCollection
from shapely.geometry       import Polygon


def main():
    polygon =  Polygon(
        shell=[ (10,10),(10,40),(70,40),(70,10),(60,10),
                (60,30),(50,30),(50,10),(10,10) ],
        holes=[ [(20,20),(40,20),(40,30),(20,30),(20,20)] ]
    )
    # print( polygon )
    
    fig, ax = plt.subplots()
    plot_polygon(ax, polygon)
    #plot_polygon(ax, polygon, facecolor='lightblue', edgecolor='red')
    plt.show()


# Plots a Polygon to pyplot `ax`
# cf. https://stackoverflow.com/questions/55522395
def plot_polygon(ax, poly, **kwargs):
    path = Path.make_compound_path(
        Path(np.asarray(poly.exterior.coords)[:, :2]),
        *[Path(np.asarray(ring.coords)[:, :2]) for ring in poly.interiors])

    patch = PathPatch(path, **kwargs)
    collection = PatchCollection([patch], **kwargs)
    
    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    return collection

    
if __name__ == '__main__':
    main()

↑こう書くと、↓こう表示されます。