# Drawing perpendicular line from existing line in Python [closed]

I want to draw a perpendicular line from the mid point of another line. For this, I could not find any function or straightforward approach.

The method I am following is, first I am creating offsets of the line on both left and right sides first with the `parallel_offset` function of `shapely` and then finding the mid point of the offset lines and connecting those. This is based on this question post but for GeoPandas data frame data.

The problem I am facing in this is, that for some lines if I am taking a larger offset distance, it is creating an empty line string for the offset. As explained in Shapely parallel_offset returning an empty list, I guess the error is occurring as the offset is vanishing at a certain distance which depends on the curvature of the original line.

I am thinking there must be a way to draw a perpendicular line from another line at any point in Python which can be drawn straightway.

How do I solve this issue?

• The "other line" is a simple line consisting of two vertices?
– BERA
Jul 7 at 11:58
• Please Edit the Question to be more specific. If the units are angular (geographic), a perpendicular line isn't actually perpendicular (or even straight). Jul 7 at 12:05

In this case Geopandas is just a way to read and write a shapefile. Geopandas geometries are shapely geometries so you can apply the same logic.

Create a function which creates a parallel line, find its centroid then draw a line from your original lines centroid to the parallel lines centroid:

``````import geopandas as gpd
from shapely.geometry import LineString

def giveline(linestring, distance):
"From a input shapely linestring, return a perpendicular linestring with the length equal to intput distance"
pline = linestring.parallel_offset(distance=distance)
return LineString([linestring.centroid, pline.centroid])

df['perpline'] = df.apply(lambda x: giveline(linestring=x.geometry, distance=200), axis=1) #Create a column of perpendicular line geometries
df2 = gpd.GeoDataFrame(df, geometry=df['perpline'], crs="EPSG:3006") #Use this to create a new dataframe
df2 = df2[['geometry']]

df2.to_file(r'/home/bera/Desktop/GIStest/BBBBB.shp')
``````

• As I have mentioned in the question, this approach is returning a empty `LineString` when the curve of line is too high and/or the offset distance is high. Jul 7 at 14:21