python - matplotlib 箭头给出 ValueError:具有多个元素的数组的真值是不明确的。使用 a.any() 或 a.all()
问题描述
当我尝试使用 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()
此错误消息与实际出现的问题几乎没有关系。我在下面给出了自己的解决方案,以便其他人可以从我的调试中学习。
解决方案
错误消息没有解释这里发生了什么:matplotlib.pyplot.arrow
和相关matplotlib.axes.Axes.arrow
的,matplotlib.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])
推荐阅读
- java - JPA/Hibernate 只写字段,没有读取
- intrinsics - 如何广播 __m256i 的最低单词?
- r - 如何使用 purrr 中的 map 和 dplyr 中的 mutate 来生成 glm 汇总表?
- uitableview - 错误当我从 tableview Swift 中删除一行时
- javascript - 使用 Jquery 删除所选项目(不在选项字段内)
- html - 如何使用按钮和HTML修复导航栏悬停问题
- language-agnostic - 迭代列表并执行两个操作的单个函数,或者每个执行自己的操作并分别迭代列表的两个函数?
- jquery - 如果标签包含“文本”隐藏父级
- php - 在 Jquery 中更改颜色输入的错误消息
- java - 未解决的参考:Kotlin 上的 LayoutParams