【发布时间】:2021-03-28 10:13:47
【问题描述】:
假设每条线包含单个点的 x 和 y 坐标,那么格式化此数组数据的最简单方法是什么,以便我可以迭代连接图形上的点?
import matplotlib.pyplot as plt
(...)
<class 'numpy.ndarray'>
[-22.58343371 7.97162262]
[-49.08400669 -28.64111278]
[-71.47754547 -25.78248676]
[-46.27120899 -21.72541444]
[ 43.6158669 109.61815799]
[-22.58343371 7.97162262]
(...)
plt.plot(x, y, color='orange')
抱歉,由于 Quang Hoang 的评论,以下几乎是完整的代码(顺序由另一个算法计算)。这显然是众所周知的 tsp 问题解决方案的一部分。当然,重点是根据列表中的正确顺序连接点,在这种情况下为:(0, 2, 1, 3, 4, 0)。
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
import numpy as np
n = 5
order = (0, 2, 1, 3, 4, 0)
distances = [[0, 39, 22, 59, 54, 33, 57, 32, 89, 73, 29, 46],
[39, 0, 20, 20, 81, 8, 49, 64, 63, 84, 10, 61],
[22, 20, 0, 39, 74, 18, 60, 44, 71, 73, 11, 46],
[59, 20, 39, 0, 93, 27, 51, 81, 48, 80, 30, 69],
[54, 81, 74, 93, 0, 73, 43, 56, 104, 76, 76, 77],
[33, 8, 18, 27, 73, 0, 45, 61, 71, 88, 8, 63],
[57, 49, 60, 51, 43, 45, 0, 85, 88, 115, 52, 103],
[32, 64, 44, 81, 56, 61, 85, 0, 74, 43, 55, 23],
[89, 63, 71, 48, 104, 71, 88, 74, 0, 38, 69, 51],
[73, 84, 73, 80, 76, 88, 115, 43, 38, 0, 81, 28],
[29, 10, 11, 30, 76, 8, 52, 55, 69, 81, 0, 55],
[46, 61, 46, 69, 77, 63, 103, 23, 51, 28, 55, 0]]
pca = PCA(n_components=2)
coord = pca.fit_transform(distances[:n])
plt.scatter(coord[:,0], coord[:,1])
for i in coord:
x = np.where(coord == i)
plt.annotate((x[0][0]) ,i, color='red')
for j in order:
print(coord[j])
plt.plot(coord[:,0], coord[:,1], color='orange')
plt.show()
【问题讨论】:
-
请贴出完整代码。另外,“连接图上的点迭代”是什么意思?
-
plt.plot(arr[:,0], arr[:,1])?
标签: python arrays numpy matplotlib plot