2013-12-17 238 views
6

我试图通过使用ggplot来包装ade4中的s.class(...)可用(部分)重现聚簇图,但这个问题实际上更为一般化。有没有办法使用ggplot创建一个“明星”阴谋?

注意:This question是指“星图”,但实际上只讨论蜘蛛图。

df  <- mtcars[,c(1,3,4,5,6,7)] 
pca <-prcomp(df, scale.=T, retx=T) 
scores <-data.frame(pca$x) 

library(ade4) 
km <- kmeans(df,centers=3) 
plot.df <- cbind(scores$PC1, scores$PC2) 
s.class(plot.df, factor(km$cluster)) 

我在寻找的基本特征是 “明星”,例如从一个公共点(这里是簇的质心)辐射到许多其他点(这里是簇中的点)的一组线。

有没有办法做到这一点使用ggplot包?如果不是直接通过ggplot,那么是否有人知道可以使用的加载项。例如,在stat_ellipse(...)上有几个变体,它不是ggplot包(herehere)的一部分。

+0

[**此**](http://stackoverflow.com/questions/18039313/pca-scaling-with-ggbiplot),[**这**](HTTP://计算器.com/questions/6578355/plotting-pca-biplot-with-ggplot2/9850141#9850141)and [** this **](http://stackoverflow.com/questions/11484133/structure-diagram-where-each-成员之间是连接到中心和所有CL)可能是有用的。 – Henrik

+0

再次感谢!所以'geom_segment(...)'就是答案。我不知道为什么我没有在文档中看到它。 – jlhoward

回答

3

这里的困难是创建数据而不是情节本身。你应该浏览这个包的代码,并提取它对你有用的东西。这应该是一个良好的开端:

enter image description here

dfxy <- plot.df 
df <- data.frame(dfxy) 
x <- df[, 1] 
y <- df[, 2] 

fac <- factor(km$cluster) 
f1 <- function(cl) { 
    n <- length(cl) 
    cl <- as.factor(cl) 
    x <- matrix(0, n, length(levels(cl))) 
    x[(1:n) + n * (unclass(cl) - 1)] <- 1 
    dimnames(x) <- list(names(cl), levels(cl)) 
    data.frame(x) 
} 
wt = rep(1, length(fac)) 
dfdistri <- f1(fac) * wt 
w1 <- unlist(lapply(dfdistri, sum)) 
dfdistri <- t(t(dfdistri)/w1) 

## create a data.frame 
cstar=2 
ll <- lapply(seq_len(ncol(dfdistri)),function(i){ 
    z1 <- dfdistri[,i] 
    z <- z1[z1>0] 
    x <- x[z1>0] 
    y <- y[z1>0] 
    z <- z/sum(z) 
    x1 <- sum(x * z) 
    y1 <- sum(y * z) 
    hx <- cstar * (x - x1) 
    hy <- cstar * (y - y1) 
    dat <- data.frame(x=x1, y=y1, xend=x1 + hx, yend=y1 + hy,center=factor(i)) 
}) 

dat <- do.call(rbind,ll) 
library(ggplot2) 
ggplot(dat,aes(x=x,y=y))+ 
    geom_point(aes(shape=center)) + 
    geom_segment(aes(yend=yend,xend=xend,color=center,group=center)) 
6

这个答案是基于@ agstudy反应,而在@ Henrik的意见提出的建议。发布是因为它更短,更直接适用于该问题。

底线是这样的:明星情节很容易用ggplot使用geom_segment(...)。使用DF,PCA,比分,和公里的问题:

# build ggplot dataframe with points (x,y) and corresponding groups (cluster) 
gg <- data.frame(cluster=factor(km$cluster), x=scores$PC1, y=scores$PC2) 
# calculate group centroid locations 
centroids <- aggregate(cbind(x,y)~cluster,data=gg,mean) 
# merge centroid locations into ggplot dataframe 
gg <- merge(gg,centroids,by="cluster",suffixes=c("",".centroid")) 
# generate star plot... 
ggplot(gg) + 
    geom_point(aes(x=x,y=y,color=cluster), size=3) + 
    geom_point(data=centroids, aes(x=x, y=y, color=cluster), size=4) + 
    geom_segment(aes(x=x.centroid, y=y.centroid, xend=x, yend=y, color=cluster)) 

结果是相同的,与s.class(...)获得。

相关问题