How to Convert Points into Coordinates with Python

How to Convert Points into Coordinates with Python

For many applications, it’s essential to know how to convert points into coordinates with Python. Whether you’re working with existing data or creating new visualizations, understanding the basics of coordinates conversion can make a world of difference. Learn in this guide how to quickly and efficiently convert between coordinates and points using the zip operator and the star operator with Python.

What are points and coordinates?

Say your data consists of a list of points, each with three coordinates, x, y and z:

data = [ [1, 2, 4], [3, 1, 9], [4, 6, 1], ..., [5, 1, 10] ]

For plotting, data analysis and whatnot it is often convenient to handle lists of coordinates rather than a list of points:

x = [1, 3, 4, ..., 5]
y = [2, 1, 6, ..., 1]
z = [4, 9, 1, ..., 10]

Have you ever wondered how to convert between one format and the other? Here is a neat way to convert points into coordinates with Python using the zip operator and the star operator.

Create a Function to Convert Points into Coordinates in Python

Let’s define a function to convert between points and coordinates. The cool thing is that the same function performs the conversion in both directions: given a list of points it produces the respective list of coordinates, and viceversa given a list of coordinates it produces the respective list of points.

With this function written, you’ll have an easy way to quickly process coordinates and points with Python!

# Initialise list of 4 points, each with 3 coordinates (x, y, z)
points = [ [1, 2, 4], [3, 1, 9], [4, 6, 1], [5, 1, 10] ]

# Function to convert between coordinates and points
def coords_points(data):

	def make(*values):
		return values

	return make(*zip(*data))

coords = coords_points(points)

print(coords)

The output of this script is, as expected

((1, 3, 4, 5), (2, 1, 6, 1), (4, 9, 1, 10))

Plotting Points in Python

A similar trick can be used to plot a list of points in Python:

def plot_list_points(L):
	import matplotlib.pyplot as plt
	plt.plot(*zip(*L), 'ro')
	plt.xlabel('x')
	plt.ylabel('y')
	plt.title('Plot a list of points in Python')
	plt.show()


points = [[1,2], [3,1], [4,5], [2,6], [3, 8]]

plot_list_points(points)

Here is the resulting plot:

Plot a list of points in Python - Convert points into coordinates with Python

I hope you’ll find this useful!

Tags:
TheDuck

Un papero in una bottiglia. Come ci è finito? Come può uscirne? La risposta gli resta straordinaria e misteriosa. A volte la intuisce, non sempre. Raramente la mette in atto, ma che gioia, che gioia quando accade! E che soffocamento rientrare nella bottiglia. /// A duck in a bottle. How did he get in there? How to get out? The answer remains mysterious and wonderful. Sometimes he grasps it, but not always; sometimes he does it, and what joy when it happens! And how suffocating to get back in.

No Comments

Post A Comment