### 主成分分析 (PCA) 图的种类及应用场景
#### 1. 散点图(Scatter Plot)
散点图是最常见的用于展示主成分得分的方式之一。通过将前两个或三个主成分作为坐标轴绘制样本点,可以直观地观察到不同类别之间的分布情况和聚集程度。
```python
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
data = load_iris()
X = data.data
y = data.target
pca = PCA(n_components=2)
principalComponents = pca.fit_transform(X)
plt.figure(figsize=(8,6))
for target in set(y):
indicesToKeep = y == target
plt.scatter(principalComponents[indicesToKeep, 0], principalComponents[indicesToKeep, 1],
label=data.target_names[target])
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')
plt.legend()
plt.show()
```
这种图形有助于理解数据集中类别的分离度以及潜在模式的存在形式[^1]。
#### 2. 变量贡献率条形图(Variance Explained Ratio Bar Chart)
该图表展示了各个主成分解释原始特征方差的比例。这可以帮助评估所选主成分数目是否合理,并判断哪些主成分携带的信息最为重要。
```python
explained_variance_ratio = pca.explained_variance_ratio_
plt.bar(range(len(explained_variance_ratio)), explained_variance_ratio, alpha=0.5,
align='center', label='individual explained variance')
plt.step(range(len(explained_variance_ratio)), np.cumsum(explained_variance_ratio),
where='mid',label='cumulative explained variance')
plt.ylabel('Explained variance ratio')
plt.xlabel('Principal components')
plt.legend(loc='best')
plt.tight_layout()
plt.show()
```
此类型的可视化对于确定最佳降维维度至关重要[^2]。
#### 3. 加载因子热力图(Loading Factors Heatmap)
加载因子反映了原变量与新构建出来的主成分间的关系强度。利用热力图能够清晰看出每一个原有属性对应于各主成分的重要性大小。
```python
loadings = pd.DataFrame(pca.components_.T * np.sqrt(pca.explained_variance_), columns=['PC1', 'PC2'])
sns.heatmap(loadings.abs(), annot=True, cmap="YlGnBu", square=True)
plt.title("Loadings heatmap")
plt.show()
```
这对于解读主成分的实际意义特别有用,尤其是在探索性数据分析阶段[^3]。
#### 4. 生物图/双标图(Biplot)
生物图结合了样品点投影和平面上箭头表示变量方向两种信息于一体。它不仅显示了个体间的相对位置关系,还提供了关于每个变量如何影响总体变异性的见解。
```python
def biplot(score, coeff , labels=None):
xs = score[:,0]
ys = score[:,1]
n = coeff.shape[0]
scalex = 1.0/(xs.max() - xs.min())
scaley = 1.0/(ys.max() - ys.min())
fig, ax = plt.subplots(figsize=(9,7))
for i in range(n): # arrows project features (ie axes)
ax.arrow(0, 0, coeff[i,0], coeff[i,1], color = 'r',alpha = 0.5)
if labels is None:
ax.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')
else:
ax.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')
for i in range(score.shape[0]):
ax.text(xs[i]*scalex*1.05, ys[i]*scaley*1.05, str(i+1), color = 'b', ha = 'right', va = 'bottom')
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)
ax.set_xlabel("PC{}".format(1))
ax.set_ylabel("PC{}".format(2))
ax.grid()
biplot(principalComponents[:,0:2], np.transpose(pca.components_[0:2, :]), list(data.feature_names))
plt.show()
```
这类图表非常适合用来同时呈现观测对象的位置及其背后驱动因素之间的联系。