# Solving Coordinate Geometry problems in Python from scratch

Updated: Mar 14

**Learn to construct your own Python functions to solve geometrical problems without importing any packages**

##
**Introduction**

Coordinate Geometry also is known as Analytical Geometry or Cartesian Geometry, used to analyze or study geometry through the means of coordinates and vertices. This concept is held in much geometrical mathematics for example to find the area of geometrical shapes using coordinates, finding the midpoints, dividing a line segment into m:n ratio, and so on. Each of these concepts has its own formulas and methodology for solving the problems. What if we are able to solve these using python?

Python, being a general-purpose programming language, is highly powerful and efficient in solving mathematical tasks or problems. Even though there are several scientific packages like NumPy and SciPy, defining our own mathematical functions and parameters on top of python would be more flexible. So, what are we going to solve? Read the concept below to know more about it.

**Concept**

In this article, we are going to solve a problem based on the triangle and a simple calculation on finding the area of the quadrilateral.

**Triangle case:** There are three mid-points of the triangle P, Q, and R whose coordinates are (12, 6), (11, 4), and (8, 4) respectively are given to us. We have to find the vertices of the triangle (A, B, and C), area of the triangle, compare the original triangle and the mid-point triangle (based on size), check collinearity, and finally plot the triangle. Of course, this problem would take four pages to come to a conclusion but, it just takes minutes to calculate in python.

**Quadrilateral case:** Four vertices A, B, C and D whose coordinates are (-4, -2), (-3, -5), (3, -2) and (2, 3) respectively are given. We have to find the area of the quadrilateral, check collinearity, and plot the quadrilateral. This is what the whole concept is going to be.

Now, let’s program and calculate it in python.

**Solving Triangle Case**

To solve the problem, the given components are just the coordinates of the mid-points. So, we have to derive the coordinates of the vertices, find the area, check collinearity, compare the original triangle versus the mid-point triangle, and finally plot both the original and mid-point triangle.

**Step-1 | Finding the coordinates of the Vertices**

The first step is going to be finding the coordinates of the vertices A, B, and C. To calculate the coordinates of the vertices, we can define a function which takes mid-points as the parameters and pass on a formula to calculate the coordinates of A, B, and C. Let’s define the function in python!

**Python Implementation: **

```
def find_triangle_coordinates(P, Q, R):
p1, p2 = P[0], P[1]
q1, q2 = Q[0], Q[1]
r1, r2 = R[0], R[1]
A = []
B = []
C = []
a1 = p1 + r1 - q1
a2 = p2 + r2 - q2
b1 = q1 + p1 - r1
b2 = q2 + p2 - r2
c1 = r1 + q1 - p1
c2 = r2 + q2 - p2
A.append(a1)
A.append(a2)
B.append(b1)
B.append(b2)
C.append(c1)
C.append(c2)
return A, B, C
```

**Code Explanation: **Firstly, we are defining a function ‘find_triangle_coordinates’ that takes the mid-points as parameters. Inside the function, we are slicing the given mid-points into single numerical variables and stored them as p1, p2, q1, q2, r1, r1. Next, we have created three empty lists named A, B, and C in which we are going to store the calculated coordinates. After that, we used a formula in which we used the sliced values of the mid-points and stored that in respective numerical variables. Explaining the formula intuitively, we are adding the first and third midpoint value and subtracting the value with the second midpoint value. Followed by that, we have appended all the calculated coordinates into the relevant vertices A, B, and C and finally returned those coordinates.

**Step-2 | Calculating the Area**

In this step, we are going to define a function for finding the area of the triangle that takes the vertices of the triangle as parameters. We will pass on a function inside the function to find the area using the coordinates of the vertices. Follow the code to define the function in python.

**Python Implementation:**

```
def find_triangle_area(A, B, C):
x1, y1 = A[0], A[1]
x2, y2 = B[0], B[1]
x3, y3 = C[0], C[1]
area = (x1*y2 + x2*y3 + x3*y1) - (y1*x2 + y2*x3 + y3*x1)
area = abs(area * 0.5)
return area
```

**Code Explanation:** Just like how we did in the previous step, we are defining a function ‘find_triangle_area’ that takes the coordinates of vertices as parameters. Inside the function, we are slicing and storing the values into the respective coordinate values. After that, we are passing a formula that takes the sliced coordinate values and calculates the area. The formula is nothing but it takes the coordinate values and crosses multiples them. To understand the formula more effectively, imagine a matrix that has all the x-coordinates in the first row and all the y-coordinates in the second row. Note that, after listing all the three x and y coordinates in the matrix, we have to add another first value of the x and y coordinate at the end of the matrix. Now, take x1 and cross multiply the value with y2, like that, x2 with y3 and x3 with y1. After calculating this part, we have to subtract it with a set of other cross multiplied values starting from y1 with x2, y2 with x3, and finally y3 with x1. Sometimes while applying this formula, we may end up with a negative result but, the area cannot be negative. So using the ‘abs’ function we are converting the sign to positive if the value is negative and multiplying the output with 0.5 or 1/2 (part of the formula). After this whole process, we are returning the final output of the function.

**Step-3 | Check Collinearity**

What is collinearity? In coordinate geometry, the vertices are said to have collinearity when the area of the triangle results in 'zero' square units. We can define a function in python which helps us to check whether the given vertices have collinearity or not.

**Python Implementation:**

```
def check_triangle_collinearity(A, B, C):
area = find_triangle_area(A, B, C)
if area == 0.0:
message = str('Given vertices {}, {}, {} are collinear'.format(A, B, C))
else:
message = str('Given vertices {}, {}, {} are not collinear'.format(A, B, C))
return message
```

**Code Explanation:** As usual, we are defining a function ‘check_triangle_collinearity’ that takes the vertices of the triangle as parameters. Inside the function, we are using the ‘find_triangle_area’ function which we defined a step ago to find the area of the triangle. After that, we passing on an if-else statement that returns true when the area which we calculated inside the function is equal to ‘zero’. If the statement gets satisfied, it returns a message saying that the given vertices are collinear. If not, it returns a message of non-collinearity.

**Step-4 | Compare the Triangles**

In this step, we are going to define a simple and minimal function that compares the given triangles and gives us a result that how many times the original triangle is bigger than the mid-point triangle. Follow the code define the function in python.

**Python Implementation:**

```
def compare_triangles(triangle_area, midpoint_area):
message = str('The area of triangle is {} times larger than the midpoint triangle'.format(int(triangle_area/midpoint_area)))
return message
```

**Code Explanation:** As I said before, this function ‘compare_triangles’ is a simple and minimal function that takes the original triangle area and the mid-point triangle area as parameters. Inside the function, we are storing a string that says how many times the original triangle is bigger than the mid-point triangle inside a variable ‘message’. Finally, we returning the message variable.

**Step-5 | Plotting the Triangle**

In this final step, we are going to define a function that makes us able to plot a triangle using the coordinates of the vertices. When it comes to plotting or graphing, without any other option we have to use the matplotlib package, or else, it takes us long to define the function. So, make sure you have matplotlib installed in your python environment. If you don’t have matplotlib installed in the python environment, then follow or copy the code and paste it into your command prompt terminal:

`pip install matplotlib`

After installing the plotting package, we are now ready to define our plot function in python.

**Python Implementation:**

```
def plot_triangle(A, B, C, color):
x1, y1 = A[0], A[1]
x2, y2 = B[0], B[1]
x3, y3 = C[0], C[1]
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (20, 10)
plt.style.use('ggplot')
fig = plt.plot([x1, x2, x3, x1], [y1, y2, y3, y1], color = color, linewidth = 2)
plt.scatter([x1, x2, x3, x1], [y1, y2, y3, y1], color = 'red', linewidth = 3)
plt.fill([x1, x2, x3, x1], [y1, y2, y3, y1], color = color, alpha = 0.3)
plt.xticks(fontsize = 14)
plt.yticks(fontsize = 14)
plt.savefig('triangle.png')
return fig
```

**Code Explanation:** We are defining a function ‘plot_triangle’ that takes the vertices of the triangle and color of the triangle as parameters. Inside the function, we are slicing the coordinates into single numerical variables (just like how we did in the preceding steps). After that, we are importing the plotting package which is the matplotlib package, and tuning some parameters to customize the size (20 inches in width and 10 inches in height) and style (ggplot) of the plot. Next, we are storing the graph into a variable ‘fig’ and finally returning the plot.

**Step-6 | The Results**

This step is the most exciting one when compared to all the others as we are going to use our defined function to solve the problem and see the results. We can use the defined function just by calling them. Without further ado, let’s implement our defined functions in python!

**Python Implementation:**

```
Pt, Qt, Rt = [12, 6], [11,4], [8,4]
At, Bt, Ct = find_triangle_coordinates([12, 6], [11,4], [8,4])
area_t = find_triangle_area(At, Bt, Ct)
area_mt = find_triangle_area(Pt, Qt, Rt)
ct = compare_triangles(area_t, area_mt)
collinearity_t = check_triangle_collinearity(At, Bt, Ct)
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl('The given midpoints are\n P = {}\n Q = {}\n R = {}'.format(Pt, Qt, Rt), attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl('The coordinates of triangle are\n A = {}\n B = {}\n C = {}'.format(At, Bt, Ct), attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl('The area of the triangle is {} sq.units'.format(area_t), attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl('The area of midpoint triangle is {} sq.units'.format(area_mt), attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl(collinearity_t, attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl(ct, attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
plot_triangle([12, 6], [11,4], [8,4], 'black')
plot_triangle(Pt, Qt, Rt, 'b')
```

Output:

Now seeing the result let’s answer all the question:

1. Find the coordinates of the vertices A, B, C

**Ans:** A = (9, 6) ; B = (15, 6) ; C = (7, 2)

2. Find the area of the triangle using the coordinates of the vertices

**Ans:** Area of the triangle = 12 square units

3. Check collinearity

**Ans:** The given vertices A, B, and C are not collinear

4. Compare the triangles

**Ans:** The original triangle is four times bigger than the mid-point triangle

5. Plot the triangle

**Ans:** Using the ‘plot_triangle’ function which we defined, we have plotted both the original and mid-point triangle.

We have successfully solved the triangle problem with the correct results. Our next case is to solve the quadrilateral problem.

**Solving Quadrilateral Case**

In this problem, our objective is to just find the area, check collinearity, and plot the quadrilateral. The given components are the vertices of the quadrilateral A, B, C, and D.

**Step-1 | Defining Quadrilateral Functions**

The functions we are going to define are most similar to the triangle functions but the only difference is that we have another vertice to add. So, there isn’t going to be any code explanation in the middle but will be there at the end. Without further ado, let’s define all the quadrilateral functions in python!

**Python Implementation:**

```
def find_quadrilateral_area(A, B, C, D):
x1, y1 = A[0], A[1]
x2, y2 = B[0], B[1]
x3, y3 = C[0], C[1]
x4, y4 = D[0], D[1]
area = (x1*y2 + x2*y3 + x3*y4 + x4*y1) - (y1*x2 + y2*x3 + y3*x4 + y4*x1)
area = abs(area * 0.5)
return area
def check_quadrilateral_collinearity(A, B, C, D):
area = find_quadrilateral_area(A, B, C, D)
if area == 0.0:
message = str('Given vertices {}, {}, {}, {} are collinear'.format(A, B, C, D))
else:
message = str('Given vertices {}, {}, {}, {} are not collinear'.format(A, B, C, D))
return message
def plot_quadrilateral(A, B, C, D, color):
x1, y1 = A[0], A[1]
x2, y2 = B[0], B[1]
x3, y3 = C[0], C[1]
x4, y4 = D[0], D[1]
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (20, 10)
plt.style.use('ggplot')
fig = plt.plot([x1, x2, x3, x4, x1], [y1, y2, y3, y4, y1], color = color, linewidth = 2)
plt.scatter([x1, x2, x3, x4, x1], [y1, y2, y3, y4, y1], color = 'b', linewidth = 3)
plt.fill([x1, x2, x3, x4, x1], [y1, y2, y3, y4, y1], color = color, alpha = 0.3)
plt.title('Quadrilateral for the given vertices A = {}, B = {}, C = {}, D = {}'.format(A, B, C, D), fontsize = 18)
plt.xticks(fontsize = 14)
plt.yticks(fontsize = 14)
return fig
```

**Code Explanation:** The first function we defined is the ‘find_quadrilateral_area’ that takes the coordinates of the vertices as parameters and calculates the area of the quadrilateral (the formula used to calculate the area of the quadrilateral is the same used to calculate the area of the triangle). The next function is the ‘check_quadrilateral_collinearity’ that takes the coordinates of the vertices as parameters and checks whether collinearity exists between the given vertices. The last function is the ‘plot_quadrilateral’ that takes the coordinates of the vertices as parameters and returns a plot of the quadrilateral and this function is built on top of the matplotlib package.

**Step-2 | The Results**

Just like how we did for the triangle problem, we are going to call the functions and use it to see the results and answer the questions. Follow the code to get the results in python.

**Python Implementation:**

```
Aq, Bq, Cq, Dq = [-4,-2], [-3,-5], [3,-2], [2,3]
area_q = find_quadrilateral_area(Aq, Bq, Cq, Dq)
collinearity_q = check_quadrilateral_collinearity(Aq, Bq, Cq, Dq)
print(cl('------------------------------------------------------------------------------------------', attrs = ['bold']))
print(cl('The coordinates of quadrilateral are A = {}, B = {}, C = {}, D = {}'.format(Aq, Bq, Cq, Dq), attrs = ['bold']))
print(cl('------------------------------------------------------------------------------------------', attrs = ['bold']))
print(cl('The area of quadrilateral is {} sq.units'.format(area_q), attrs = ['bold']))
print(cl('------------------------------------------------------------------------------------------', attrs = ['bold']))
print(cl(collinearity_q, attrs = ['bold']))
print(cl('------------------------------------------------------------------------------------------', attrs = ['bold']))
```

Output:

After seeing the results, let’s solve the quadrilateral problem by answering all the questions.

1. Find the area of the quadrilateral

**Ans:** The area of the quadrilateral is 28 square units

2. Check collinearity

**Ans:** The given vertices are not collinear

3. Plot the quadrilateral

**Ans:** Using the ‘plot_quadrilateral’ function, we have plotted the quadrilateral.

That’s it! We have successfully completed all of our problems optimally using our own defined functions python.

**Final Thoughts!**

After a whole bunch of coding and mathematical calculations, we have successfully done all the problems. You might think that this style of solving coordinate geometry problems takes more time than doing it manually in a notebook because we are learning the concepts newly and introduced the world of programming to solve these kinds of problems. Solving and calculating problems manually will help you just to an extent but not throughout the journey. Solving it in a digital way and especially on your own work will give you more confidence to do more things and stretches your mind to gain more knowledge. Remember that it takes time but it’s never worthless. With that, you have come to the end of this article, and don’t worry if you forgot to follow any of the coding parts as I’ve provided the full source code at the end of the article. Never ever stop learning, push your own limits, and do wonders!

**Full code:**

```
def find_triangle_coordinates(P, Q, R):
p1, p2 = P[0], P[1]
q1, q2 = Q[0], Q[1]
r1, r2 = R[0], R[1]
A = []
B = []
C = []
a1 = p1 + r1 - q1
a2 = p2 + r2 - q2
b1 = q1 + p1 - r1
b2 = q2 + p2 - r2
c1 = r1 + q1 - p1
c2 = r2 + q2 - p2
A.append(a1)
A.append(a2)
B.append(b1)
B.append(b2)
C.append(c1)
C.append(c2)
return A, B, C
def find_triangle_area(A, B, C):
x1, y1 = A[0], A[1]
x2, y2 = B[0], B[1]
x3, y3 = C[0], C[1]
area = (x1*y2 + x2*y3 + x3*y1) - (y1*x2 + y2*x3 + y3*x1)
area = abs(area * 0.5)
return area
def check_triangle_collinearity(A, B, C):
area = find_triangle_area(A, B, C)
if area == 0.0:
message = str('Given vertices {}, {}, {} are collinear'.format(A, B, C))
else:
message = str('Given vertices {}, {}, {} are not collinear'.format(A, B, C))
return message
def compare_triangles(triangle_area, midpoint_area):
message = str('The area of triangle is {} times larger than the midpoint triangle'.format(int(triangle_area/midpoint_area)))
return message
def plot_triangle(A, B, C, color):
x1, y1 = A[0], A[1]
x2, y2 = B[0], B[1]
x3, y3 = C[0], C[1]
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (20, 10)
plt.style.use('ggplot')
fig = plt.plot([x1, x2, x3, x1], [y1, y2, y3, y1], color = color, linewidth = 2)
plt.scatter([x1, x2, x3, x1], [y1, y2, y3, y1], color = 'red', linewidth = 3)
plt.fill([x1, x2, x3, x1], [y1, y2, y3, y1], color = color, alpha = 0.3)
plt.xticks(fontsize = 14)
plt.yticks(fontsize = 14)
plt.savefig('triangle.png')
return fig
def find_quadrilateral_area(A, B, C, D):
x1, y1 = A[0], A[1]
x2, y2 = B[0], B[1]
x3, y3 = C[0], C[1]
x4, y4 = D[0], D[1]
area = (x1*y2 + x2*y3 + x3*y4 + x4*y1) - (y1*x2 + y2*x3 + y3*x4 + y4*x1)
area = abs(area * 0.5)
return area
def check_quadrilateral_collinearity(A, B, C, D):
area = find_quadrilateral_area(A, B, C, D)
if area == 0.0:
message = str('Given vertices {}, {}, {}, {} are collinear'.format(A, B, C, D))
else:
message = str('Given vertices {}, {}, {}, {} are not collinear'.format(A, B, C, D))
return message
def plot_quadrilateral(A, B, C, D, color):
x1, y1 = A[0], A[1]
x2, y2 = B[0], B[1]
x3, y3 = C[0], C[1]
x4, y4 = D[0], D[1]
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (20, 10)
plt.style.use('ggplot')
fig = plt.plot([x1, x2, x3, x4, x1], [y1, y2, y3, y4, y1], color = color, linewidth = 2)
plt.scatter([x1, x2, x3, x4, x1], [y1, y2, y3, y4, y1], color = 'b', linewidth = 3)
plt.fill([x1, x2, x3, x4, x1], [y1, y2, y3, y4, y1], color = color, alpha = 0.3)
plt.title('Quadrilateral for the given vertices A = {}, B = {}, C = {}, D = {}'.format(A, B, C, D), fontsize = 18)
plt.xticks(fontsize = 14)
plt.yticks(fontsize = 14)
return fig
# Triangle
from termcolor import colored as cl
import matplotlib.pyplot as plt
Pt, Qt, Rt = [12, 6], [11,4], [8,4]
At, Bt, Ct = find_triangle_coordinates([12, 6], [11,4], [8,4])
area_t = find_triangle_area(At, Bt, Ct)
area_mt = find_triangle_area(Pt, Qt, Rt)
ct = compare_triangles(area_t, area_mt)
collinearity_t = check_triangle_collinearity(At, Bt, Ct)
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl('The given midpoints are\n P = {}\n Q = {}\n R = {}'.format(Pt, Qt, Rt), attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl('The coordinates of triangle are\n A = {}\n B = {}\n C = {}'.format(At, Bt, Ct), attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl('The area of the triangle is {} sq.units'.format(area_t), attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl('The area of midpoint triangle is {} sq.units'.format(area_mt), attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl(collinearity_t, attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
print(cl(ct, attrs = ['bold']))
print(cl('----------------------------------------------------------------------', attrs = ['bold']))
plot_triangle(At, Bt, Ct, 'black')
plot_triangle(Pt, Qt, Rt, 'b')
# Quadrilateral
Aq, Bq, Cq, Dq = [-4,-2], [-3,-5], [3,-2], [2,3]
area_q = find_quadrilateral_area(Aq, Bq, Cq, Dq)
collinearity_q = check_quadrilateral_collinearity(Aq, Bq, Cq, Dq)
print(cl('------------------------------------------------------------------------------------------', attrs = ['bold']))
print(cl('The coordinates of quadrilateral are A = {}, B = {}, C = {}, D = {}'.format(Aq, Bq, Cq, Dq), attrs = ['bold']))
print(cl('------------------------------------------------------------------------------------------', attrs = ['bold']))
print(cl('The area of quadrilateral is {} sq.units'.format(area_q), attrs = ['bold']))
print(cl('------------------------------------------------------------------------------------------', attrs = ['bold']))
print(cl(collinearity_q, attrs = ['bold']))
print(cl('------------------------------------------------------------------------------------------', attrs = ['bold']))
plot_quadrilateral(Aq, Bq, Cq, Dq, 'r')
```