簡體   English   中英

R - 添加質心以散點圖

[英]R - add centroids to scatter plot

我有一個數據集兩個連續變量和一個因子變量(兩個類)。 我想創建一個帶有兩個質心(每個類一個)的散點圖,其中包含R中的誤差條。質心應位於每個類的x和y的平均值。

我可以使用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))

這是你的想法嗎?

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 ,列xyclass ,其中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%的置信度而不是std。 錯誤,替換

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM