matplotlib箭头给出ValueError:具有多个元素的数组的真值不明确。使用a.any()或a.all()

时间:2018-09-03 22:25:20

标签: python matplotlib

当我尝试使用matplotlib的arrow函数绘制箭头时出现错误。

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> arrow_start = np.random.normal(0, 1, [100, 2])
>>> arrow_vector = np.random.normal(0, 0.05, [100, 2])
>>> plt.arrow(x=arrow_start[:, 0], y=arrow_start[:, 1], 
...           dx=arrow_vector[:, 0], dy=arrow_vector[:, 1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\programdata\miniconda3\lib\site-packages\matplotlib-2.2.2-py3.6-win-amd64.egg\matplotlib\axes\_axes.py", line 4844, in arrow
    a = mpatches.FancyArrow(x, y, dx, dy, **kwargs)
  File "c:\programdata\miniconda3\lib\site-packages\matplotlib-2.2.2-py3.6-win-amd64.egg\matplotlib\patches.py", line 1255, in __init__
    if not length:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

此错误消息与实际发生的错误几乎没有关系。我在下面给出了自己的解决方案,以便其他人可以从调试中学习。

1 个答案:

答案 0 :(得分:0)

该错误消息不能解释此处的情况:matplotlib.pyplot.arrow和关联的matplotlib.axes.Axes.arrowmatplotlib.patches.FancyArrow不支持一次绘制多个箭头。

使用类似的方法可以轻松解决该问题

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> arrow_start = np.random.normal(0, 1, [100, 2])
>>> arrow_vector = np.random.normal(0, 0.05, [100, 2])
>>> for i in range(len(arrow_start.shape[0])):
...     plt.arrow(x=arrow_start[i, 0], y=arrow_start[i, 1], 
...               dx=arrow_vector[i, 0], dy=arrow_vector[i, 1])