我註釋與matplotlib陰謀與此代碼和元素與NumPy的
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處形成兩個箭頭,在彼此的頂部。相反,我想對力量進行求和,只在力位4 + 5 = 9時在位置1創建一個箭頭,在力位8 + 9 = 17時在位置4創建一個箭頭。
我該怎麼用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)',但這顯然不是這樣的。 – Iguananaut