首页 > 解决方案 > matplotlib pylot 发生异常:ValueError

问题描述

我用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版本是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()

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

标签: pythonmatplotlib

解决方案


Matplotlib 期望在 0.0 和 1.0 之间的范围内指定 RGB(A) 颜色,请在此处查看更多信息。下面的修复会更改 (0, 1) 内的颜色。此外,它在艺术家对象上使用 set_color 方法。不完全确定为什么您的代码不应该工作。我会看看它。

编辑:它实际上在没有设置线的情况下开箱即用,但颜色必须在 0、1 以内!

在此处输入图像描述

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

推荐阅读