我想在 x,y 散点图上生成 10 个不同的点,并且会有一条路径可以通过每个点并返回到起点。
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()
答案 0 :(得分:1)
尝试做
plt.plot(x1,y1)
此解决方案来自 this 线程,我将立即在我的机器上试用。
编辑:这不会连接端点。改为这样做:
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()