Kush
Kush

Reputation: 11

How to use Shapely to plot squares/rectangles along a centre line

How can Shapely be used to plot squares/rectangles along a centre line?

A sketch of what I am trying to achieve

In the sketch above, I would like to plot the red squares along the black line. The black line is a collection of (x, y) points.

Upvotes: 1

Views: 891

Answers (1)

primitivist
primitivist

Reputation: 875

from shapely.geometry import LineString, Point, box
import matplotlib.pyplot as plt
import numpy as np

# let's use a sine curve as our example line
x = np.arange(0, 3 * np.pi, 0.5)
y = np.sin(x)
xy = list(zip(x, y))
line = LineString(xy)
plt.plot(*line.xy)

# let's sample every 3 points along the line
x_samp = x[::3]
y_samp = y[::3]
plt.scatter(x_samp, y_samp)

# generate boxes along sampled points on the line
radius = (x_samp[1] - x_samp[0]) / 2
for i in range(len(x_samp)):
    box_loc = box(*Point(x_samp[i], y_samp[i]).buffer(radius).bounds)
    plt.plot(*box_loc.exterior.xy)

plt.axes().set_aspect('equal')
plt.show()

enter image description here

Upvotes: 2

Related Questions