2014-05-05 66 views
4

我有一个数据集连续的两个变量和一个因素变量(2类)。我想创建与两个质心(每个类)的散点图,其包括在R.误差棒的质心的位置应在x和y为每个类的平均值。的R - 添加到质心散点图

我可以轻松地创建使用GGPLOT2散点图,但我无法弄清楚如何添加的重心。使用ggplot/qplot可以做到这一点吗?

下面是一些示例代码:

x <- c(1,2,3,4,5,2,3,5) 
y <- c(10,11,14,5,7,9,8,5) 
class <- c(1,1,1,0,0,1,0,0) 
df <- data.frame(class, x, y) 
qplot(x,y, data=df, color=as.factor(class)) 

回答

11

这是你脑子里有什么?

centroids <- aggregate(cbind(x,y)~class,df,mean) 
ggplot(df,aes(x,y,color=factor(class))) + 
    geom_point(size=3)+ geom_point(data=centroids,size=5) 

这就产生了一个单独的数据帧,centroids,与yx,和class其中xy是由类的平均值。然后我们使用centroid作为数据集添加第二个点几何图层。

这是一个稍微有趣的版本,可用于聚类分析。

gg <- merge(df,aggregate(cbind(mean.x=x,mean.y=y)~class,df,mean),by="class") 
ggplot(gg, aes(x,y,color=factor(class)))+geom_point(size=3)+ 
    geom_point(aes(x=mean.x,y=mean.y),size=5)+ 
    geom_segment(aes(x=mean.x, y=mean.y, xend=x, yend=y)) 

编辑回应OP的评论。

使用geom_errorbar(...)geom_errorbarh(...)可以添加垂直和水平误差条。

centroids <- aggregate(cbind(x,y)~class,df,mean) 
f   <- function(z)sd(z)/sqrt(length(z)) # function to calculate std.err 
se  <- aggregate(cbind(se.x=x,se.y=y)~class,df,f) 
centroids <- merge(centroids,se, by="class") # add std.err column to centroids 
ggplot(gg, aes(x,y,color=factor(class)))+ 
    geom_point(size=3)+ 
    geom_point(data=centroids, size=5)+ 
    geom_errorbar(data=centroids,aes(ymin=y-se.y,ymax=y+se.y),width=0.1)+ 
    geom_errorbarh(data=centroids,aes(xmin=x-se.x,xmax=x+se.x),height=0.1) 

如果你想计算,比方说,95%的置信度,而不是性病。错误,与

f <- function(z) qt(0.025,df=length(z)-1, lower.tail=F)* sd(z)/sqrt(length(z)) 
+0

这是伟大的替代

f <- function(z)sd(z)/sqrt(length(z)) # function to calculate std.err 

,谢谢。是否也可以将水平和垂直条添加到表示x和y值的标准误差的质心? – cyril

+0

请参阅最后的编辑。 – jlhoward

+0

谢谢!太棒了。 – cyril