這是你腦子裏有什麼?
![](https://i.stack.imgur.com/hRzZY.png)
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
,與y
列x
,和class
其中x
和y
是由類的平均值。然後我們使用centroid
作爲數據集添加第二個點幾何圖層。
這是一個稍微有趣的版本,可用於聚類分析。
![](https://i.stack.imgur.com/gJBmm.png)
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)
![](https://i.stack.imgur.com/YWK3v.png)
如果你想計算,比方說,95%的置信度,而不是性病。錯誤,與
f <- function(z) qt(0.025,df=length(z)-1, lower.tail=F)* sd(z)/sqrt(length(z))
這是偉大的替代
,謝謝。是否也可以將水平和垂直條添加到表示x和y值的標準誤差的質心? – cyril
請參閱最後的編輯。 – jlhoward
謝謝!太棒了。 – cyril