Scott Gigante
Scott Gigante

Reputation: 1635

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

I am getting an error when I attempt to draw arrows using matplotlib's arrow function.

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

This error message has very little to do with what is actually going wrong. I have given my own solution below, so others can learn from my debugging.

Upvotes: 1

Views: 1422

Answers (1)

Scott Gigante
Scott Gigante

Reputation: 1635

The error message does not explain what's going on here: matplotlib.pyplot.arrow and associated matplotlib.axes.Axes.arrow, matplotlib.patches.FancyArrow do not support plotting more than one arrow at a time.

The issue is easily resolved with something like

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

Upvotes: 3

Related Questions