Matplotlib图例(不同结果)

qgzx9mmu  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(115)

我是matplotlib的新手,但我在使用python list和numpy数组时发现了不同之处。

  • Python列表代码
import matplotlib.pyplot as plt
    import numpy as np
    
    names = ['Sunny','Bunny','Chinny','Vinny','Pinny']
    marks = np.array([700,300,600,400,100])
    x = np.arange(len(names)) #[0,1,2,3,4]
    y = x
    scat = plt.scatter(x,y,s=marks,c=x,cmap='prism')
    plt.legend(handles=scat.legend_elements()[0],labels=names)
    plt.show()
  • numpy数组码
import matplotlib.pyplot as plt
    import numpy as np
    
    names = np.array(['Sunny','Bunny','Chinny','Vinny','Pinny'])
    marks = np.array([700,300,600,400,100])
    x = np.arange(names.size) #[0,1,2,3,4]
    y = x
    scat = plt.scatter(x,y,s=marks,c=x,cmap='prism')
    plt.legend(handles=scat.legend_elements()[0],labels=names)
    plt.show()

为什么我在numpy数组代码中得到一个错误?这是错误:

Exception has occurred: ValueError
    The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
fcwjkofz

fcwjkofz1#

当你设置图例时,你需要传入names数组作为一个列表,像这样:

plt.legend(handles=scat.legend_elements()[0],labels=list(names))

如果你查看原始代码的错误追溯,它会在这里失败:

1307     # if got both handles and labels as kwargs, make same length
-> 1308     if handles and labels:
   1309         handles, labels = zip(*zip(handles, labels))
   1310 

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

if handles and labels期望labels参数是一个列表,传递一个numpy数组会引发ValueError。它可能应该是一个TypeError,如果你愿意,你可以在他们的存储库中提出一个问题。

相关问题