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[]
user
5,1497 gold badges46 silver badges70 bronze badges
asked Feb 16, 2017 at 18:30
1
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
DSH
91013 silver badges24 bronze badges
answered Feb 16, 2017 at 20:31
Aziz AltoAziz Alto
17.5k4 gold badges72 silver badges57 bronze badges
7
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[]
answered Feb 16, 2017 at 19:44
fugledefuglede
16.4k2 gold badges54 silver badges89 bronze badges
Your main problem is you create new figures in your loop, so each vector gets drawn on a different figure. Here's what I came up with, let me know if it's still not what you expect:
CODE:
import numpy as np
import matplotlib.pyplot as plt
M = np.array[[[1,1],[-2,2],[4,-7]]]
rows,cols = M.T.shape
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax[abs[M], axis = 0]
for i,l in enumerate[range[0,cols]]:
xs = [0,M[i,0]]
ys = [0,M[i,1]]
plt.plot[xs,ys]
plt.plot[0,0,'ok'] #