Voronoi not plotting real time data tuple index out of range

╄→尐↘猪︶ㄣ 提交于 2020-05-09 17:15:07

问题


I'm trying to plot a voronoi diagram with real time data, but get the error:

IndexError: tuple index out of range

the code:

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)

code and error

The value of the data variable is like this: [b' 0,2036377.2,04291.', b' 0,2027879.2,040747.'].

Any idea how to fix this?


回答1:


As mentioned in the comments, the error you are getting is because you are passing the wrong input to Voronoi, please read the documentation

Regarding what you are trying to do and assuming that the data you get from data, addr = sock.recvfrom(1024) is like this [b' 0,2036377.2,04291.', b' 0,2027879.2,040747.'] you then have to do address the following points:

  • decode the bytes to string
  • extract the coordinates using for example a regular expression
  • convert the string representation of the coordinates to float
  • organise the data structure to create a Voronoi diagram

The code you have so far address most of these points but it does not structure the data as the input for the Voronoi diagram.

The code bellow addressed all the points and will create the Voronoi diagram for you:

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()

The result is the following: Imgur



来源:https://stackoverflow.com/questions/61358938/voronoi-not-plotting-real-time-data-tuple-index-out-of-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!