【发布时间】:2015-05-06 17:25:04
【问题描述】:
我正在用 matplotlib 用这段代码注释一个绘图
for position, force in np.nditer([positions, forces]):
plt.annotate(
"%.3g N" % force,
xy=(position, 3),
xycoords='data',
xytext=(position, 2.5),
textcoords='data',
horizontalalignment='center',
arrowprops=dict(arrowstyle="->")
)
它工作正常。但是如果我在同一个位置有元素,它会将多个箭头相互堆叠,即如果我有positions = [1,1,4,4] 和forces = [4,5,8,9],它将在位置 1 处创建两个箭头,在位置 4 处创建两个箭头,在每个箭头的顶部其他。相反,我想对力求和,只在位置 1 创建一个箭头,力为 4+5=9,在位置 4 创建一个箭头,力为 8+9=17。
如何使用 Python 和 NumPy 做到这一点?
编辑
我猜可能是这样的
import numpy as np
positions = np.array([1,1,4,4])
forces = np.array([4,5,8,9])
new_positions = np.unique(positions)
new_forces = np.zeros(new_positions.shape)
for position, force in np.nditer([positions, forces]):
pass
【问题讨论】:
-
我想知道这个问题是否有更好的标题。对我来说,“对数组中的元素求和”只是意味着
np.sum(array),但这显然不是这个意思。
标签: python arrays numpy matplotlib