在散点图中添加质心

7

我有一个数据集,包含两个连续变量和一个因子变量(两个类别)。我想在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))
2个回答

20

这是你想要的吗?

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))

编辑 回应原帖评论。

可以使用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%置信度而不是标准误差,请将 </p> 替换为:
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)) 

太好了,谢谢。是否可以在质心上添加水平和垂直条形图,以表示x和y值的标准误差? - cyril
谢谢!这很完美。 - cyril

0

我没能让 @jlhoward 给出的代码(特别是涉及误差条的部分)完全正常工作,所以我做了一些微小的修改以消除错误和警告。现在你应该能够从头到尾地运行这段代码了,如果 @jlhoward 愿意将这些修改融入到原有的答案中,那就太好了。

centroids <- aggregate(cbind(mean.x = x, mean.y = y) ~ class, df, mean)
gg        <- merge(df, centroids, by = "class")
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 = x, y = y, color = factor(class))) +
  geom_point(size = 3) +
  geom_point(data = centroids, aes(x = mean.x, y = mean.y), size = 5) +
  geom_errorbar(data = centroids, 
                aes(x = mean.x, y = mean.y, ymin = mean.y - se.y, ymax = mean.y + se.y),
                width = 0.1) +
  geom_errorbarh(data = centroids, inherit.aes=FALSE, # keeps ggplot from using first aes
                 aes(xmin = (mean.x - se.x), xmax = (mean.x + se.x), y = mean.y,
                 height = 0.1, color = factor(class))) +
  labs(x = "Label for x-axis", y = "Label for y-axis") +
  theme(legend.title = element_blank()) # remove legend title

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接