- Plotting a Single 2D Vector
This code defines a 2D vector v = [2, 5], creates a new plot using matplotlib, and then plots the vector as an arrow starting at the origin (0, 0).
The angles, scale_units, and scale parameters control the appearance of the arrowhead and the scaling of the arrow.
Finally, the code sets the limits and labels for the plot and displays it. You should see a plot with a 2D vector pointing from the origin (0, 0) to the point (2, 5).
import matplotlib.pyplot as plt
# Define the vector
v = [2,5]
# Plot the vector as an arrow
plt.quiver(0, 0, v[0], v[1], angles="xy", scale_units="xy", scale = 1, color="Red")
# Set the limits for the plot
plt.xlim([-5, 5])
plt.ylim([-5, 5])
# Set the labels for the plot
plt.xlabel('X')
plt.ylabel('Y')
# Show the grid lines
plt.grid()
# Show the plot
plt.show()
About “quiver()” Function
quiver(x, y, u, v, angles='xy', scale_units='xy', scale=1, **kwargs)
The quiver() function takes several arguments:
- x and y are the x and y coordinates of the starting points of the arrows. These can be scalars or arrays of the same shape as u and v.
- u and v are the x and y components of the arrows. These can also be scalars or arrays of the same shape as x and y.
- angles specifies the units of the angles that the arrowheads make with the x-axis. The default value is ‘xy’, which means that the angles are measured in radians from the positive x-axis.
- scale_units specifies the units of the arrow length. The default value is ‘xy’, which means that the arrow length is scaled by the x and y data limits.
- scale is a scaling factor that is applied to the arrow length. The default value is 1, which means that the arrow length is not scaled.
- **kwargs are additional optional keyword arguments that can be used to customize the appearance of the arrows. Some commonly used kwargs include color to set the color of the arrows, alpha to set the opacity, and linewidth to set the width of the arrow lines.
The quiver() function returns a Quiver object, which represents the collection of arrows in the plot.
- Plotting Multiple 2D Vectors
import matplotlib.pyplot as plt
# Define the vectors
#vector1
v1 = [2,5]
#vector2
v2 = [6,8]
# Plot the first vector (v1) as an arrow
plt.quiver(0, 0, v1[0], v1[1], angles="xy", scale_units="xy", scale = 1, color="Red")
# Plot the second vector (v2) as an arrow
plt.quiver(0, 0, v2[0], v2[1], angles="xy", scale_units="xy", scale = 1, color="Blue")
# Set the limits for the plot
plt.xlim([0, 10])
plt.ylim([0, 10])
# Set the labels for the plot
plt.xlabel('X')
plt.ylabel('Y')
# Show the grid lines
plt.grid()
# Show the plot
plt.show()