我正在尝试绘制具有实时数据的voronoi图,但出现错误:
IndexError: tuple index out of range
代码:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
data = str(data, "utf-8") #convert bytes into string and fix the 'b'
#data.decode("utf-8", errors="ignore")
data = data.strip(" ").split(".")
x = data[0]
y = data[1]
x = float(x.replace( ',', '.'))
y = float(y.replace( ',', '.'))
vor = Voronoi(x,y)
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9oaEdhby5wbmcifQ==” alt =“代码和错误”>
data
变量的值是这样的:[b' 0,2036377.2,04291.', b' 0,2027879.2,040747.']
。
任何想法如何解决此问题?
如评论中所述,收到的错误是因为您将错误的输入传递给Voronoi
,请阅读documentation
关于您要做什么,并假设您从data
获得的data, addr = sock.recvfrom(1024)
像这样[b' 0,2036377.2,04291.', b' 0,2027879.2,040747.']
,那么您必须解决以下几点:
float
Voronoi
图到目前为止,您拥有的代码已解决了大多数这些问题,但它并未将数据构成为Voronoi
图的输入。
下面的代码解决了所有问题,并将为您创建Voronoi
图:
import re
from scipy.spatial import Voronoi, voronoi_plot_2d
import matplotlib.pyplot as plt
import doctest
doctest.testmod() # used to test the docstring
# compile the regular expression used to parse the input data
regex = re.compile(' (\d+,\d+)\.(\d+,\d+)\.')
def parse_data(data):
"""
parse a list of strings with x, y coordinates
>>> data = [b' 0,2036377.2,04291.', b' 0,2027879.2,040747.']
>>> parse_data(data)
[[0.2036377, 2.04291], [0.2027879, 2.040747]]
"""
proc_data = []
for i in data:
m = regex.match(i.decode('utf-8')) # decode the bytes and match the regex
if m:
# parse the coordinates and organise the data structure
proc_data += [[float(m.group(1).replace(',','.')),
float(m.group(2).replace(',','.'))]]
return proc_data
data = [b' 0,2036377.2,04291.', b' 0,2027879.2,040747.',
b' 0,2018921.2,037455.', b' 0,2010467.2,034439.',
b' 0,2004007.2,031721.', b' 0,1996321.2,027795.',
b' 0,1989551.2,023898.', b' 0,1983429.2,020666.',
b' 0,1978466.2,017263.']
data = parse_data(data)
vor = Voronoi(data) # create the Voronoi diagram with correct input data
voronoi_plot_2d(vor)
plt.show()
结果如下: