Home > Software design >  Multiple arrows on the same plot using Matplotlib
Multiple arrows on the same plot using Matplotlib

Time:07-03

I want to have multiple arrows on the same plot using the list I6. In I6[0], (0.5, -0.5) represent x,y coordinate of the arrow base and (1.0, 0.0) represent the length of the arrow along x,y direction. The meanings are the same for I6[1],I6[2],I6[3] But the code runs into an error.

import matplotlib.pyplot as plt

I6=[[(0.5, -0.5), (1.0, 0.0)], [(0.5, -0.5), (0.0, -1.0)], [(1.5, -0.5), (0.0, -1.0)], [(0.5, -1.5), (1.0, 0.0)]]

for i in range(0,len(I6)): 
    plt.arrow(I6[i][0], I6[i][1], width = 0.05)
    plt.show()

The error is

in <module>
    plt.arrow(I6[i][0], I6[i][1], width = 0.05)

TypeError: arrow() missing 2 required positional arguments: 'dx' and 'dy'

CodePudding user response:

The solution is to unpack the coordinates and lengths from the data matrix correctly, as

(x, y), (u, v) = element 

Then, the plot can either be done with quiver or arrow as shown in these two examples below.

import matplotlib.pyplot as plt

I6 = [
    [(0.5, -0.5), (1.0, 0.0)], 
    [(0.5, -0.5), (0.0, -1.0)], 
    [(1.5, -0.5), (0.0, -1.0)], 
    [(0.5, -1.5), (1.0, 0.0)]
]

# Solution with arrow
for element in I6:
    (x, y), (dx, dy) = element
    plt.arrow(x, y, dx, dy, head_width=0.02, color="k")

plt.show()

# Solution with quiver
plt.figure()
for element in I6:
    (x, y), (dx, dy) = element
    plt.quiver(x, y, dx, dy, scale=1, units="xy", scale_units="xy")

plt.show()

arrows with matplotlib arrow function arrows with matplotlib quiver function

CodePudding user response:

Instead of plotting arrows in matplotlib with arrow(), use quiver() to avoid issues with list values:

import matplotlib.pyplot as plt

I6=[[(0.5, -0.5), (1.0, 0.0)], [(0.5, -0.5), (0.0, -1.0)], [(1.5, -0.5), (0.0, -1.0)], [(0.5, -1.5), (1.0, 0.0)]]

for i in range(len(I6)):
    plt.quiver(I6[i][0], I6[i][1], width = 0.05)
plt.show()

In this case, the arrows seem to be too thick and with a small modulus, you can adjust this by changing the input values of your list I6 enter image description here

  • Related