【问题标题】:PCA projection plot with ggplot2带有ggplot2的PCA投影图
【发布时间】:2014-08-04 17:00:33
【问题描述】:

我有一个图,它演示了将点投影到具有最大方差的轴上的想法。 R 中的代码粘贴在下面,我需要一个初始指针如何在ggplot2 中重现此图。

# Simulate data
library(mvtnorm)
set.seed(2014)
Sigma <- matrix(data = c(4, 2, 2, 3), ncol=2)
mu <- c(1, 2)
n <- 20
X <- rmvnorm(n = n, mean = mu, sigma = Sigma)

# Run PCA
pca <- princomp(X)
load <- loadings(pca)
slope <- load[2, ] / load[1, ]
cmeans <- apply(X, 2, mean)
intercept <- cmeans[2] - (slope * cmeans[1])

# Plot data & 1st principal component
plot(X, pch = 20, asp = 1)
abline(intercept[1], slope[1])

# Plot perpendicular segments
x1 <- (X[, 2] - intercept[1]) / slope[1]
y1 <- intercept[1] + slope[1] * X[, 1]
x2 <- (x1 + X[, 1]) / 2
y2 <- (y1 + X[, 2]) / 2
segments(X[, 1], X[, 2], x2, y2, col = "red")

【问题讨论】:

    标签: r plot ggplot2 principal-components


    【解决方案1】:

    将矩阵 X 和向量 x2 和 y2 放在一个数据框中。

    df<-data.frame(X,x2,y2)
    

    然后将列 X1、X2 用作 xy 值,将 x2 和 y2 用作 xend=yend=。使用geom_point() 添加点,使用geom_abline() 添加直线,使用geom_segment() 添加线段。使用coord_fixed(),您可以确保 x 轴和 y 轴的宽度相同。

    library(ggplot2)
    ggplot(df,aes(X1,X2))+
          geom_point()+
          geom_abline(intercept=intercept[1],slope=slope[1])+
          geom_segment(aes(xend=x2,yend=y2),color="red")+
          coord_fixed()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 2016-08-02
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      • 2017-11-24
      • 1970-01-01
      相关资源
      最近更新 更多