Newyen minh
Newyen minh

Reputation: 13

Generate random points and generating a path for it

I would like to generate 10 different points on an x,y scatterplot and there would be a path that could go through every point and return to the starting point.

import random
import matplotlib.pyplot as plt

num_points = 10
x1 = [random.randrange(start=1, stop=10) for i in range(num_points)]
x2 = [random.randrange(start=1, stop=10) for i in range(num_points)]
y1 = [random.randrange(start=1, stop=10) for i in range(num_points)]
y2 = [random.randrange(start=1, stop=10) for i in range(num_points)]
xy1 = [x1,y1]

plt.scatter(x1, y1, c='blue')
plt.scatter(x2, y2, c='red')
plt.show()

result: scatterplot of 10 points

goal: this was done via paint

Upvotes: 0

Views: 538

Answers (1)

Michael J
Michael J

Reputation: 11

try doing

plt.plot(x1,y1)

This solution was from this thread, and I will try on my machine momentarily.

edit: this doesn't connect the endpoints. do this instead:

import random
import matplotlib.pyplot as plt

num_points = 10
x1 = [random.randrange(start=1, stop=10) for i in range(num_points)]
x2 = [random.randrange(start=1, stop=10) for i in range(num_points)]
y1 = [random.randrange(start=1, stop=10) for i in range(num_points)]
y2 = [random.randrange(start=1, stop=10) for i in range(num_points)]
xy1 = [x1,y1]


plt.scatter(x1, y1, c='blue')
plt.scatter(x2, y2, c='red')
plt.plot(x1,y1,c='blue')
plt.plot([x1[0],x1[-1]],[y1[0],y1[-1]],c='blue') #connects first and last point
plt.plot(x2,y2,c='red')
plt.plot([x2[0],x2[-1]],[y2[0],y2[-1]],c='red') #connects first and last point in second set

plt.show()  

Upvotes: 1

Related Questions