Данные графика PCA FactoMineR

Я запускаю сценарий R, генерирующий графики анализа PCA, используя FactorMineR.

Я хотел бы вывести координаты для сгенерированных графиков PCA, но у меня возникли проблемы с поиском правильных координат. Я нашел results1$ind$coord и results1$var$coord, но ни один из них не похож на график по умолчанию.

Я нашел http://www.statistik.tuwien.ac.at/public/filz/students/seminar/ws1011/hoffmann_ausarbeitung.pdf и http://factominer.free.fr/classical-methods/principal-components-analysis.html, но не описывает содержимое переменной, созданной PCA

library(FactoMineR)
data1 <- read.table(file=args[1], sep='\t', header=T, row.names=1)
result1 <- PCA(data1,ncp = 4, graph=TRUE) # graphs generated automatically
plot(result1)

person Community    schedule 20.04.2012    source источник
comment
я думаю, что нашел данные в $ind$coord, он просто не пометил их правильно   -  person    schedule 21.04.2012
comment
args[1] не является воспроизводимой ссылкой. Если вы хотите отредактировать свой Q, чтобы он ссылался на набор данных, который находится в пакете, вы получите больше внимания.   -  person IRTFM    schedule 21.04.2012
comment
@DWin спасибо, это хороший момент   -  person    schedule 21.04.2012
comment
Возможно, вам следует опубликовать ответ, а затем поставить себе галочку после подходящего интервала. Всегда нужны проработанные примеры.   -  person IRTFM    schedule 21.04.2012
comment
@DWin Я сделаю это :) Мне нужно подождать 8 часов, потому что у меня все еще недостаточно репутации   -  person    schedule 21.04.2012
comment
Вас может заинтересовать ggbiplot.   -  person chl    schedule 22.04.2012


Ответы (3)


Я обнаружил, что $ind$coord[,1] и $ind$coord[,2] являются первыми двумя координатами PCA в объекте PCA. Вот рабочий пример, который включает в себя несколько других вещей, которые вы, возможно, захотите сделать с выводом PCA...

# Plotting the output of FactoMineR's PCA using ggplot2
#
# load libraries
library(FactoMineR)
library(ggplot2)
library(scales)
library(grid)
library(plyr)
library(gridExtra)
#
# start with a clean slate
rm(list=ls(all=TRUE)) 
#
# load example data
data(decathlon)
#
# compute PCA
res.pca <- PCA(decathlon, quanti.sup = 11:12, quali.sup=13, graph = FALSE)
#
# extract some parts for plotting
PC1 <- res.pca$ind$coord[,1]
PC2 <- res.pca$ind$coord[,2]
labs <- rownames(res.pca$ind$coord)
PCs <- data.frame(cbind(PC1,PC2))
rownames(PCs) <- labs
#
# Just showing the individual samples...
ggplot(PCs, aes(PC1,PC2, label=rownames(PCs))) + 
  geom_text() 

введите здесь описание изображения

# Now get supplementary categorical variables
cPC1 <- res.pca$quali.sup$coor[,1]
cPC2 <- res.pca$quali.sup$coor[,2]
clabs <- rownames(res.pca$quali.sup$coor)
cPCs <- data.frame(cbind(cPC1,cPC2))
rownames(cPCs) <- clabs
colnames(cPCs) <- colnames(PCs)
#
# Put samples and categorical variables (ie. grouping
# of samples) all together
p <- ggplot() + theme(aspect.ratio=1) + theme_bw(base_size = 20) 
# no data so there's nothing to plot...
# add on data 
p <- p + geom_text(data=PCs, aes(x=PC1,y=PC2,label=rownames(PCs)), size=4) 
p <- p + geom_text(data=cPCs, aes(x=cPC1,y=cPC2,label=rownames(cPCs)),size=10)
p # show plot with both layers

введите здесь описание изображения

# Now extract the variables
#
vPC1 <- res.pca$var$coord[,1]
vPC2 <- res.pca$var$coord[,2]
vlabs <- rownames(res.pca$var$coord)
vPCs <- data.frame(cbind(vPC1,vPC2))
rownames(vPCs) <- vlabs
colnames(vPCs) <- colnames(PCs)
#
# and plot them
#
pv <- ggplot() + theme(aspect.ratio=1) + theme_bw(base_size = 20) 
# no data so there's nothing to plot
# put a faint circle there, as is customary
angle <- seq(-pi, pi, length = 50) 
df <- data.frame(x = sin(angle), y = cos(angle)) 
pv <- pv + geom_path(aes(x, y), data = df, colour="grey70") 
#
# add on arrows and variable labels
pv <- pv + geom_text(data=vPCs, aes(x=vPC1,y=vPC2,label=rownames(vPCs)), size=4) + xlab("PC1") + ylab("PC2")
pv <- pv + geom_segment(data=vPCs, aes(x = 0, y = 0, xend = vPC1*0.9, yend = vPC2*0.9), arrow = arrow(length = unit(1/2, 'picas')), color = "grey30")
pv # show plot 

введите здесь описание изображения

# Now put them side by side in a single image
#
grid.arrange(p,pv,nrow=1)
# 
# Now they can be saved or exported...

введите здесь описание изображения

person Ben    schedule 20.04.2012
comment
Не волнуйтесь. Я обнаружил, что ребята из списка адресов электронной почты FactorMineR также очень полезны. - person Ben; 21.04.2012

Добавление чего-то дополнительного к ответу Бена. На первой диаграмме в ответе Бена вы заметите, что метки несколько перекрываются. Функция pointLabel() в пакете maptools пытается найти места для меток без перекрытия. Это не идеально, но вы можете настроить позиции в кадре данных new (см. ниже), чтобы точно настроить, если хотите. (Кроме того, когда вы загружаете maptools, вы получаете примечание о gpclibPermit(). Вы можете игнорировать его, если вас беспокоит ограниченная лицензия). Первая часть сценария ниже — это сценарий Бена.

# load libraries
library(FactoMineR)
library(ggplot2)
library(scales)
library(grid)
library(plyr)
library(gridExtra)
#
# start with a clean slate
# rm(list=ls(all=TRUE)) 
#
# load example data
data(decathlon)
#
# compute PCA
res.pca <- PCA(decathlon, quanti.sup = 11:12, quali.sup=13, graph = FALSE)
#
# extract some parts for plotting
PC1 <- res.pca$ind$coord[,1]
PC2 <- res.pca$ind$coord[,2]
labs <- rownames(res.pca$ind$coord)
PCs <- data.frame(cbind(PC1,PC2))
rownames(PCs) <- labs 
#

# Now, the code to produce Ben's first chart but with less overlap of the labels.

library(maptools)

PCs$label=rownames(PCs)

# Base plot first for pointLabels() to get locations
plot(PCs$PC1, PCs$PC2, pch = 20, col = "red")
new = pointLabel(PCs$PC1, PCs$PC2, PCs$label, cex = .7)
new = as.data.frame(new)
new$label = PCs$label

# Then plot using ggplot2
(p = ggplot(data = PCs) + 
   geom_hline(yintercept = 0, linetype = 3, colour = "grey20") +
   geom_vline(xintercept = 0, linetype = 3, colour = "grey20") +
   geom_point(aes(PC1, PC2), shape = 20, col = "red") +
   theme_bw())

(p = p +  geom_text(data = new, aes(x, y, label = label), size = 3))

Результат:

введите здесь описание изображения

person Sandy Muspratt    schedule 21.04.2012
comment
Согласен, текст на моих графиках немного загроможден. Уменьшение размера в geom_text может немного помочь. Спасибо, что показали функцию pointLabel, я ее раньше не видел! - person Ben; 21.04.2012

Альтернативой является использование функции biplot из CoreR или biplot.psych из пакета psych. Это поместит компоненты и данные на одну и ту же фигуру.

Для набора данных десятиборья используйте принципала и двойную диаграмму из пакета psych:

 library(FactoMineR) #needed to get the example data
 library(psych)  #needed for principal 
 data(decathlon)  #the data set
 pc2 <- principal(decathlon[1:10],2) #just the first 10 columns
 biplot(pc2,labels = rownames(decathlon),cex=.5, main="Biplot of Decathlon results") 
 #this is a call to biplot.psych which in turn calls biplot.
 #adjust the cex parameter to change the type size of the labels.

Это выглядит так:

!http://personality-project.org/r/images/olympic.biplot.pdf

Счет

person William Revelle    schedule 09.06.2013