# Generate random polygons within another polygon using shapely in python

I have a use case where given a polygon on the US map, I need to generate n rectangles within the polygon defined on the US map. I have been trying stuff with shapely, but stuck.

So the code would work in this way.

1. Define the upper level polygon
``````poly = Polygon([(-123.52380921651545,44.92842807389871), (-115.78943421651545,32.651610397456906),(-81.95154359151545,33.71815014381751),(-78.74353577901545,39.29454038362893),(-91.57556702901545,42.223006851069464),(-106.29724671651545,45.207760924293545),(-123.52380921651545,44.92842807389871)])
``````
1. Write function which takes polygon defined in step 1, and number of rectangles that need to be created within that polygon.
``````def random_polygon (poly, num_polygons, points_per_poly=4):
min_x, min_y, max_x, max_y = poly.bounds
random_poly = []
while len(random_poly) < num_polygons:
``````
1. What is the syntax in this piece, where I generate a random rectangle, where the length and breadth is fixed, but the co-ordinates are different for each rectangle. Once the rectangle is generated I check if it is within bounds of polygon created in Step 1. If yes I add it to random_poly and continue.
• Can those polygons overlap? Jun 10, 2022 at 21:08

Steps:

1. Define a random point for each axis within the bounds.
2. Assume that to be top-left point and create a rectangle.
3. check if that rectangle is within the outer polygon
``````import random

from shapely.geometry import Polygon, Point
poly = Polygon([(-123.52380921651545,44.92842807389871), (-115.78943421651545,32.651610397456906),(-81.95154359151545,33.71815014381751),(-78.74353577901545,39.29454038362893),(-91.57556702901545,42.223006851069464),(-106.29724671651545,45.207760924293545),(-123.52380921651545,44.92842807389871)])

min_x, min_y, max_x, max_y = poly.bounds

width = # to be defined
height = # to be defined
num_polygons = # to be defined
random_poly = []

while len(random_poly) < num_polygons:
rand_x = random.uniform(min_x, max_x)
rand_y = random.uniform(min_y, max_y)

left = Point([rand_x, rand_y])
bottom = Point([rand_x, rand_y - height])
right = Point([rand_x + width, rand_y - height])
top = Point([rand_x + width, rand_y])

new_poly = Polygon([left, bottom, right, top])

if poly.contains(new_poly):
random_poly.append(new_poly)
``````