关于ggplot2:R-将质心添加到散点图

R - add centroids to scatter plot

我有一个数据集,其中包含两个连续变量和一个因子变量(两个类)。我想创建一个散点图,其中包含两个质心(每个类一个),其中包括R中的误差线。质心应位于每个类的x和y的平均值处。

我可以使用ggplot2轻松创建散点图,但是我不知道如何添加质心。是否可以使用ggplot / qplot做到这一点?

这是一些示例代码:

1
2
3
4
5
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))

这是您的初衷吗?

> </p>
<div class=

1
2
3
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作为数据集添加第二个点几何层。

这是一个稍微有趣的版本,在聚类分析中很有用。

> </p>
<div class=

1
2
3
4
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))

EDIT对OP评论的回复。

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

1
2
3
4
5
6
7
8
9
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)

> </p>
<p>例如,要计算95%的置信度而不是标准差。错误,替换</p>
<div class=

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

with

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