如何为PCA累计方差图的指定点绘制至坐标轴的连线?
实现PCA累计方差图的坐标轴连线效果
需求说明
要在PCA累计方差曲线图中,给指定点(比如累计方差达到80%的位置)添加连接到x轴和y轴的辅助连线,预期效果为:曲线对应点向下画垂直线到x轴,向左画水平线到y轴,同时标记该点。
修改方案
通过matplotlib的辅助线函数和标记点功能即可实现,以下是完整修改后的代码:
from sklearn.decomposition import PCA import numpy as np import matplotlib.pyplot as plt # 计算完整PCA的累计方差 pca = PCA() pca.fit(x) cumulative_variance = np.cumsum(pca.explained_variance_ratio_) # 定位目标点坐标(以累计方差≥0.8为例) target_variance = 0.8 # 找到第一个满足条件的组件数(索引+1对应实际组件数量) n_components = np.argmax(cumulative_variance >= target_variance) + 1 target_y = cumulative_variance[n_components - 1] # 绘制累计方差曲线 plt.figure() plt.plot(cumulative_variance, marker='o', markersize=4) # 绘制辅助连线 plt.vlines(x=n_components, ymin=0, ymax=target_y, color='red', linestyle='--') plt.hlines(y=target_y, xmin=0, xmax=n_components, color='red', linestyle='--') # 标记目标点 plt.scatter(n_components, target_y, color='red', s=50, zorder=5) # 添加图表标注 plt.xlabel('Number of Components') plt.ylabel('Cumulative Variance Ratio') plt.title('Explained Cumulative Variance') plt.grid(alpha=0.3) plt.show() # 后续降维代码保留 pca = PCA(n_components=0.8) new_data = pca.fit_transform(x) print("Selected components' explained variance ratio:", pca.explained_variance_ratio_) print("Absolute values of PCA components:\n", abs(pca.components_))
关键逻辑说明
np.argmax(cumulative_variance >= target_variance) + 1:精准定位第一个满足累计方差要求的组件数量(因数组索引从0开始,需+1匹配实际组件数)plt.vlines/plt.hlines:分别绘制垂直、水平辅助虚线,用红色虚线区分于主曲线plt.scatter:用红色圆点突出目标点,zorder=5确保点显示在最上层
内容的提问来源于stack exchange,提问作者Hose Orlando
相关产品推荐
相关产品推荐

