简体   繁体   English

凸多边形R中的主成分分析双图

[英]Principal Components Analysis biplot in R with convex polygons

I've produced attached biplot using the following code: 我使用以下代码生成了附加的biplot:

dd = data.frame(x = runif(10), y=runif(10)) 
pcr = prcomp(~x + y, data=dd)
biplot(pcr)

This produces a biplot showing the axis for x and Y and each of the 10 data points. 这将产生一个双线图,显示x和Y的轴以及10个数据点中的每一个。

Lets say that the 10 data points are made up of 2 different groups, (5 in one group, 5 in the other group). 可以说,这10个数据点由2个不同的组组成(一组中的5个,另一组中的5个)。 How can I produce a biplot with a Minimum Convex Polygon around each group, to show a division for the 2 groups? 我如何在每组周围生成一个具有最小凸多边形的Biplot,以显示两个组的划分?

I looked into stats:::biplot.default and stats:::biplot.prcomp and i'm close to what you want. 我调查了stats ::: biplot.defaultstats ::: biplot.prcomp ,我很接近您想要的。 You can modify this code to suit your need. 您可以修改此代码以适合您的需要。 ( I used the iris dataset ) (我使用了虹膜数据集)

require(plyr)

data(iris)

pcr <- prcomp(~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris)

indiv <- data.frame(pcr$x[,1:2])

indiv$species <- iris$Species

column <- data.frame(pcr$rotation[ ,1:2])

n <- nrow(indiv)

eigenval <- pcr$sdev[1:2]

eigenval <- eigenval * sqrt(n)

indiv <- transform(indiv, pc1 = PC1 / eigenval[1], pc2  = PC2 / eigenval[2])

column <- transform(column, pc1 = PC1 * eigenval[1], pc2  = PC2 * eigenval[2])

### based on stats:::biplot.default

unsigned.range <- function(x) c(-abs(min(x, na.rm = TRUE)),  abs(max(x, na.rm = TRUE)))

rangx1 <- unsigned.range(indiv[, 4])
rangx2 <- unsigned.range(indiv[, 5])
rangy1 <- unsigned.range(column[, 3])
rangy2 <- unsigned.range(column[, 4])

mylim <- range(rangx1, rangx2)
ratio <- max(rangy1/rangx1, rangy2/rangx2)

nspecies <- table(iris$Species)

# compute the convex hull for each species
hull <- dlply(indiv[,1:3], .(species), chull)

# get points connected
hull <- llply(hull, function(x) c(x, x[1]))


plot(pc2 ~ pc1, data = indiv, cex = 0.5, col = c("blue", "yellow", "green")[iris$Species], xlim = mylim, ylim = mylim)

lines(indiv$pc1[hull$setosa], indiv$pc2[hull$setosa] , col = "blue")

lines(indiv$pc1[cumsum(nspecies)[1] + hull$versicolor], indiv$pc2[cumsum(nspecies)[1] + hull$versicolor], col = "yellow")

lines(indiv$pc1[cumsum(nspecies)[2] + hull$virginica],  indiv$pc2[cumsum(nspecies)[2] + hull$virginica], col = "green")

par(new = TRUE)

plot(pc1 ~ pc2, data = column, axes = FALSE, type = "n", xlim = mylim * ratio, ylim = mylim * ratio, xlab = "", ylab = "")

text(column$pc1, column$pc2, labels = rownames(column), cex = 0.5, col = "red")

arrows(0, 0, column$pc1 * 0.8, column$pc2 * 0.8, col = "red", length = 0.2)

axis(3, col = "red")

axis(4, col = "red")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM