slothfulwave612
slothfulwave612

Reputation: 1409

Adding multiple arrows to produce a resultant arrow

Let's say I have a various number of arrows in a matplotlib plot, these arrows are of different length and are pointing towards different directions, the following image is a visual explanation:

enter image description here

Here is the code snippet that produces the above plot:

fig, ax = plt.subplots(figsize=(12,8))
ax.set(xlim=(0, 10), ylim=(0,10))

ax.arrow(5, 5, 2, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k')
ax.arrow(4.8, 5, -2, -2, head_width=0.05, head_length=0.1, fc='k', ec='k')
ax.arrow(4.8, 5.3, -1.5, -2.6, head_width=0.05, head_length=0.1, fc='k', ec='k')
ax.arrow(4.8, 5.7, -3.5, -0.6, head_width=0.05, head_length=0.1, fc='k', ec='k')
ax.arrow(4.9, 5, 2, 2, head_width=0.05, head_length=0.1, fc='k', ec='k')
ax.arrow(4.5, 6.2, 2.2, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k')
ax.arrow(5.5, 4.2, 2.6, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k')
ax.arrow(4.5, 4.2, 1.7, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k')
ax.arrow(6.5, 6.2, 0.4, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k')

Now, what I want is: I want to plot a resultant arrow that is produced by adding all these arrows(the same way we add multiple vectors to generate one resultant vector), i.e. we have to calculate which direction the resultant arrow will be pointing towards and the average length of the resultant arrow.(the starting point of the resulting arrow should be at let say (5,5))

I am finding it difficult to solve this problem. Can somebody help?

Upvotes: 1

Views: 744

Answers (1)

Léonard
Léonard

Reputation: 2630

Adding arrows does not take into account the starting points of each arrow. An arrow just show how to get from a point (undefined) to another with a dx and dy, as the 3rd and 4rth arguments of the ax.quiver function.

That being said, if you include every dxs and dys of your arrows in two lists, then it becomes easier:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(12,8))
ax.set(xlim=(0, 10), ylim=(0,10))

x0, y0 = 5, 5
dxs = [2, -2, -1.5, -3.5, 2, 2.2, 2.6, 1.7, 0.4]
dys = [0.5, -2, -2.6, -0.6, 2, 0.5, 0.5, 0.5, 0.5]

# show each individual arrow
for dx, dy in zip(dxs, dys):
    ax.arrow(x0, y0, dx, dy, head_width=0.05, head_length=0.1, fc='k', ec='k')

# show the resultant arrow
ax.arrow(x0, y0, sum(dxs), sum(dys), head_width=0.05, head_length=0.1, fc='r', ec='r')

plt.show()

Note that all the arrows have been arbitrarily "attached" to the same starting point (5, 5) for the sake of clarity. Every arrow can however have a different starting point, but only the dx and dy can add up (as explained on this wiki page for instance).

Here is the output of the above code, with the red arrow being the resultant one: vector addition in matplotlib

Upvotes: 1

Related Questions