2014-05-05 118 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