为何使用numpy数组的matplotlib代码出现模糊真值ValueError?
为什么numpy数组版本的Matplotlib代码会触发ValueError?
作为Matplotlib新手,我发现使用Python列表与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()
报错信息:
Exception has occurred: ValueError
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
原因分析:
问题出在plt.legend()的labels参数上——Matplotlib的这个参数只接受原生Python序列类型(比如列表、元组),不直接支持numpy数组作为输入。
当传入numpy数组时,Matplotlib内部逻辑会尝试对输入的labels进行布尔值判断(比如检查是否为空),而numpy数组包含多个元素,无法直接返回单一布尔值,因此抛出"真值判断歧义"的错误。
解决方法:
把numpy数组转换为Python列表即可,修改plt.legend行的labels参数:
plt.legend(handles=scat.legend_elements()[0], labels=names.tolist())
内容的提问来源于stack exchange,提问作者doughstone
相关产品推荐
相关产品推荐

