我是 matplotlib 的新手,但是当我使用 python list 和 numpy array 进行编码时,我发现了差异。
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 数组代码中遇到错误? 这是错误:
发生异常:ValueError
具有多个元素的数组的真值是不明确的。使用 a.any() 或 a.all()
设置图例时,您需要将名称数组作为列表传递,如下所示:
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
,如果您愿意,可以在他们的存储库中提出问题。