I am taking a course on linear algebra and I want to visualize the vectors in action, such as vector addition, normal vector, so on.
For instance:
V = np.array([[1,1],[-2,2],[4,-7]])
In this case I want to plot 3 vectors V1 = (1,1), M2 = (-2,2), M3 = (4,-7)
.
Then I should be able to add V1,V2 to plot a new vector V12(all together in one figure).
when I use the following code, the plot is not as intended
import numpy as np import matplotlib.pyplot as plt M = np.array([[1,1],[-2,2],[4,-7]]) print("vector:1") print(M[0,:]) # print("vector:2") # print(M[1,:]) rows,cols = M.T.shape print(cols) for i,l in enumerate(range(0,cols)): print("Iteration: {}-{}".format(i,l)) print("vector:{}".format(i)) print(M[i,:]) v1 = [0,0],[M[i,0],M[i,1]] # v1 = [M[i,0]],[M[i,1]] print(v1) plt.figure(i) plt.plot(v1) plt.show()
In this article, we are going to discuss how to plot a vector field in python. In order to perform this task we are going to use the quiver() method and the streamplot() method in matplotlib module. Where X, Y define the Vector location and U, V are directional arrows with respect of the Vector location.
You can visualize a vector field by plotting vectors on a regular grid, by plotting a selection of streamlines, or by using a gradient color scheme to illustrate vector and streamline densities. You can also plot a vector field from a list of vectors as opposed to a mapping.
We can also plot vector fields in three dimensions, i.e., for functions F:R3→R3. The principle is exactly the same; we plot vectors of length proportional to F(x,y,z) with tail anchored at the point (x,y,z).
How about something like
import numpy as np import matplotlib.pyplot as plt V = np.array([[1,1], [-2,2], [4,-7]]) origin = np.array([[0, 0, 0],[0, 0, 0]]) # origin point plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21) plt.show()
Then to add up any two vectors and plot them to the same figure, do so before you call plt.show()
. Something like:
plt.quiver(*origin, V[:,0], V[:,1], color=['r','b','g'], scale=21) v12 = V[0] + V[1] # adding up the 1st (red) and 2nd (blue) vectors plt.quiver(*origin, v12[0], v12[1]) plt.show()
NOTE: in Python2 use origin[0], origin[1]
instead of *origin
This may also be achieved using matplotlib.pyplot.quiver
, as noted in the linked answer;
plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1) plt.xlim(-10, 10) plt.ylim(-10, 10) plt.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With