matplotlib pylot发生了异常:ValueError

时间:2019-03-14 09:07:36

标签: python matplotlib

当我使用matplotlib绘制图片时,pylot的scatter方法显示了一个异常,该异常信息如下:

 Exception has occurred: ValueError
 'c' argument has 797 elements, which is not acceptable for use with 'x' 
  with size 797, 'y' with size 797.
  File "D:\legao\xiaowy\plot.py", line 74, in <module>
  plt.scatter(x, y, c=color)

python verison是3.6,matplotlib是3.0.2。

我阅读了帮助文档,但没有发现具体错误。请帮助我找出答案,谢谢。

我的代码如下:

import math
import matplotlib.pyplot as plt

# data
traces = {
    'A': [(112, 36), (112, 45), (112, 52), (112, 54), (112, 63), (111, 73), 
          (111, 86), (111, 91), (111, 97), (110, 105)],
    'B': [(119, 37), (120, 42), (121, 54), (121, 55), (123, 64), (124, 74), 
          (125, 87), (127, 94), (125, 100), (126, 108)],
    'C': [(93, 23), (91, 27), (89, 31), (87, 36), (85, 42), (82, 49), (79, 
          59), (74, 71), (70, 82), (62, 86), (61, 92), (55, 101)],
    'D': [(118, 30), (124, 83), (125, 90), (116, 101), (122, 100)],
    'E': [(77, 27), (75, 30), (73, 33), (70, 37), (67, 42), (63, 47), (59, 
          53), (55, 59), (49, 67), (43, 75), (36, 85), (27, 92), (24, 97), 
          (20, 102)],
    'F': [(119, 30), (120, 34), (120, 39), (122, 59), (123, 60), (124, 70), 
          (125, 82), (127, 91), (126, 97), (128, 104)],
    'G': [(88, 37), (87, 41), (85, 48), (82, 55), (79, 63), (76, 74), (72, 
          87), (67, 92), (65, 98), (60, 106)],
    'H': [(124, 35), (123, 40), (125, 45), (127, 59), (126, 59), (128, 67), 
          (130, 78), (132, 88), (134, 93), (135, 99), (135, 107)],
    'I': [(98, 26), (97, 30), (96, 34), (94, 40), (92, 47), (90, 55), (87, 
          64), (84, 77), (79, 87), (74, 93), (73, 102)],
    'J': [(123, 60), (125, 63), (125, 81), (127, 93), (126, 98), (125, 100)]
}


def get_vector(a, b):
    """Calculate vector (distance, angle in degrees) from point a to point 
       b.

      Angle ranges from -180 to 180 degrees.
      Vector with angle 0 points straight down on the image.
      Values increase in clockwise direction.
    """
    dx = float(b[0] - a[0])
    dy = float(b[1] - a[1])

    distance = math.sqrt(dx**2 + dy**2)

    if dy > 0:
        angle = math.degrees(math.atan(-dx/dy))
    elif dy == 0:
        if dx < 0:
            angle = 90.0
        elif dx > 0:
            angle = -90.0
        else:
            angle = 0.0
    else:
        if dx < 0:
            angle = 180 - math.degrees(math.atan(dx/dy))
        elif dx > 0:
            angle = -180 - math.degrees(math.atan(dx/dy))
        else:
            angle = 180.0

    return distance, angle


def count_distance():
    '''Loop through the point data and calculate the result and color 
    values'''

    x = []
    y = []
    c = []
    red_c = (255, 0, 0)
    blue_c = (0, 0, 255)
    for group1 in traces.keys():
        for index1, point1 in enumerate(traces[group1]):
            for group2 in traces.keys():
                for index2, point2 in enumerate(traces[group2]):
                    if point1 != point2 and index2 - index1 == 1:
                        t1, t2 = get_vector(point1, point2)
                        x.append(t2)
                        y.append(t1)
                        if group1 == group2:
                            c.append(blue_c)
                        else:
                            c.append(red_c)
    return x, y, c


if __name__ == '__main__':
    x, y, color = count_distance()
    # print(len(x))
    # exception here
    plt.scatter(x, y, c=color)
    plt.xlabel('Angle')
    plt.ylabel('Distance')
    plt.show()

首先,我初始化了一批运动数据(轨迹),然后设计了一个函数(get_vector)来计算两点之间的距离。函数count_distance统计轨迹中所有点的距离以及应显示的颜色。代码错误主要是由颜色数据引起的。

2 个答案:

答案 0 :(得分:1)

Matplotlib期望在0.0到1.0之间指定RGB(A)颜色,更多here。下面的修复程序更改(0,1)中的颜色。此外,它在艺术家对象上使用set_color方法。整个人不知道为什么您的代码不起作用。我来看看。

编辑:它实际上是开箱即用的,没有设定的行,但是着色器必须在0、1之内!

enter image description here

import math
import matplotlib.pyplot as plt

# data
traces = {
    'A': [(112, 36), (112, 45), (112, 52), (112, 54), (112, 63), (111, 73), 
          (111, 86), (111, 91), (111, 97), (110, 105)],
    'B': [(119, 37), (120, 42), (121, 54), (121, 55), (123, 64), (124, 74), 
          (125, 87), (127, 94), (125, 100), (126, 108)],
    'C': [(93, 23), (91, 27), (89, 31), (87, 36), (85, 42), (82, 49), (79, 
          59), (74, 71), (70, 82), (62, 86), (61, 92), (55, 101)],
    'D': [(118, 30), (124, 83), (125, 90), (116, 101), (122, 100)],
    'E': [(77, 27), (75, 30), (73, 33), (70, 37), (67, 42), (63, 47), (59, 
          53), (55, 59), (49, 67), (43, 75), (36, 85), (27, 92), (24, 97), 
          (20, 102)],
    'F': [(119, 30), (120, 34), (120, 39), (122, 59), (123, 60), (124, 70), 
          (125, 82), (127, 91), (126, 97), (128, 104)],
    'G': [(88, 37), (87, 41), (85, 48), (82, 55), (79, 63), (76, 74), (72, 
          87), (67, 92), (65, 98), (60, 106)],
    'H': [(124, 35), (123, 40), (125, 45), (127, 59), (126, 59), (128, 67), 
          (130, 78), (132, 88), (134, 93), (135, 99), (135, 107)],
    'I': [(98, 26), (97, 30), (96, 34), (94, 40), (92, 47), (90, 55), (87, 
          64), (84, 77), (79, 87), (74, 93), (73, 102)],
    'J': [(123, 60), (125, 63), (125, 81), (127, 93), (126, 98), (125, 100)]
}


def get_vector(a, b):
    """Calculate vector (distance, angle in degrees) from point a to point 
       b.

      Angle ranges from -180 to 180 degrees.
      Vector with angle 0 points straight down on the image.
      Values increase in clockwise direction.
    """
    dx = float(b[0] - a[0])
    dy = float(b[1] - a[1])

    distance = math.sqrt(dx**2 + dy**2)

    if dy > 0:
        angle = math.degrees(math.atan(-dx/dy))
    elif dy == 0:
        if dx < 0:
            angle = 90.0
        elif dx > 0:
            angle = -90.0
        else:
            angle = 0.0
    else:
        if dx < 0:
            angle = 180 - math.degrees(math.atan(dx/dy))
        elif dx > 0:
            angle = -180 - math.degrees(math.atan(dx/dy))
        else:
            angle = 180.0

    return distance, angle


def count_distance():
    '''Loop through the point data and calculate the result and color 
    values'''

    x = []
    y = []
    c = []
    red_c = (1, 0, 0)
    blue_c = (0, 0, 1)
    for group1 in traces.keys():
        for index1, point1 in enumerate(traces[group1]):
            for group2 in traces.keys():
                for index2, point2 in enumerate(traces[group2]):
                    if point1 != point2 and index2 - index1 == 1:
                        t1, t2 = get_vector(point1, point2)
                        x.append(t2)
                        y.append(t1)
                        if group1 == group2:
                            c.append(blue_c)
                        else:
                            c.append(red_c)
    return x, y, c


if __name__ == '__main__':
    x, y, color = count_distance()
    # print(len(x))
    # exception here
    h = plt.scatter(x, y, c = color)

    plt.xlabel('Angle')
    plt.ylabel('Distance')
    plt.show()

答案 1 :(得分:-1)

plt.scatter(x, y, c=color)

由于您使用的是c = color,因此需要一个因子(仅限某些级别的分类变量)。该错误说明了所有问题,发生了 Exception:ValueError  'c'参数具有797个元素,不能与'x'一起使用   的大小为797,“ y”的大小为797。

这意味着matplotlib将不允许使用x和y级别相等的变量。 只需删除c =颜色并尝试对其进行绘制,就可以了。