Change loadings (arrows) length in PCA plot using ggplot2/ggfortify?

…衆ロ難τιáo~ 提交于 2019-12-04 07:01:29

This answer is probably long after the OP needs it, but I'm offering it because I have been wrestling with the same issue for a while, and maybe I can save someone else the same effort.

# Load data
DATA <- data.frame(iris)

# Do PCA
PCA <- prcomp(iris[,1:4])

# Extract PC axes for plotting
PCAvalues <- data.frame(Species = iris$Species, PCA$x)

# Extract loadings of the variables
PCAloadings <- data.frame(Variables = rownames(PCA$rotation), PCA$rotation)

    # Plot
ggplot(PCAvalues, aes(x = PC1, y = PC2, colour = Species)) +
  geom_segment(data = PCAloadings, aes(x = 0, y = 0, xend = (PC1*5),
     yend = (PC2*5)), arrow = arrow(length = unit(1/2, "picas")),
     color = "black") +
  geom_point(size = 3) +
  annotate("text", x = (PCAloadings$PC1*5), y = (PCAloadings$PC2*5),
     label = PCAloadings$Variables)

In order to increase the arrow length, multiply the loadings for the xend and yend in the geom_segment call. With a bit of trial and effort, can work out what number to use.

To place the labels in the correct place, multiply the PC axes by the same value in the annotate call.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!