Summary:
I am trying to plot the largest and smallest eigen vectors of 2-dimensional data in python using numpy and matplotlib. I used the numpy functions for covariance matrix, eigen values and eigen vectors. Later, I tried to plot the eigen vectors using quiver plot for the given data. The eigen vectors do not show up correctly. I guess there is some mistake in the way in which I am plotting the quiver plot. Can someone guide me what is the right way ?
This is my code :
import numpy as np
import matplotlib.pyplot as plt
from numpy import array
from numpy import linalg as LA
# Assume that I loaded 'N' no of 2d points from a file and used
# np.cov() to find the below covariance matrix
# This is my covariance matrix obtained from 2 x N points
cov_mat = [[3407.3108669 1473.06388943]
[1473.06388943 1169.53151003]]
eigen_values, eigen_vectors = LA.eig(cov_mat)
origin = [0, 0]
eig_vec1 = eigen_vectors[:,0]
eig_vec2 = eigen_vectors[:,1]
# This line below plots the 2d points
#plt.scatter(np_array[:,0], np_array[:,1])
plt.quiver(origin, eig_vec1, color=['r'], scale=21)
plt.quiver(origin, eig_vec2, color=['b'], scale=21)
plt.show()
My Output:
This is my 2D data. We can see the largest eigen vector is supposed to be in the diagonal direction. But the vector does not show up correctly in the plot.
You're indeed using quiver wrong. X
, Y
, U
, and V
should be separate arguments (See the documentation for details). With plt.quiver(*origin, *eig_vec1, color=['r'], scale=21)
(i.e. unpacking your origin and eigenvectors) you should get the desired result.
import numpy as np
import matplotlib.pyplot as plt
from numpy import array
from numpy import linalg as LA
# Assume that I loaded 'N' no of 2d points from a file and used
# np.cov() to find the below covariance matrix
# This is my covariance matrix obtained from 2 x N points
cov_mat = [[3407.3108669, 1473.06388943],
[1473.06388943, 1169.53151003]]
eigen_values, eigen_vectors = LA.eig(cov_mat)
origin = [0, 0]
eig_vec1 = eigen_vectors[:,0]
eig_vec2 = eigen_vectors[:,1]
print(eig_vec1)
print(eig_vec2)
# This line below plots the 2d points
#plt.scatter(np_array[:,0], np_array[:,1])
plt.quiver(*origin, *eig_vec1, color=['r'], scale=21)
plt.quiver(*origin, *eig_vec2, color=['b'], scale=21)
plt.show()
gives the following plot: