如何在 python 中使用 numpy 和 matplotlib 绘制二维数据的最大和最小特征向量?

How to plot largest and smallest eigen vectors, for 2-dimensional data using numpy and matplotlib in python?

总结:

我正在尝试使用 numpy 和 matplotlib 在 python 中绘制二维数据的最大和最小特征向量。我将 numpy 函数用于协方差矩阵、特征值和特征向量。后来,我尝试使用颤抖图为给定数据绘制特征向量。特征向量未正确显示。我想我绘制箭袋图的方式有一些错误。有人可以指导我什么是正确的方法吗?

这是我的代码:

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()

我的输出:

这是我的二维数据。我们可以看到最大的特征向量应该在对角线方向。但是矢量在图中没有正确显示。

你确实用错了箭袋。 XYUV 应该是单独的参数(有关详细信息,请参阅 documentation)。使用 plt.quiver(*origin, *eig_vec1, color=['r'], scale=21)(即解包你的原点和特征向量)你应该得到想要的结果。

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()

给出如下图: