简体   繁体   English

R - 添加质心以散点图

[英]R - add centroids to scatter plot

I have a dataset two continuous variables and one factor variable (two classes). 我有一个数据集两个连续变量和一个因子变量(两个类)。 I want to create a scatterplot with two centroids (one for each class) that includes error bars in R. The centroids should be positioned at the mean values for x and y for each class. 我想创建一个带有两个质心(每个类一个)的散点图,其中包含R中的误差条。质心应位于每个类的x和y的平均值。

I can easily create the scatter plot using ggplot2, but I can't figure out how to add the centroids. 我可以使用ggplot2轻松创建散点图,但我无法弄清楚如何添加质心。 Is it possible to do this using ggplot / qplot? 是否可以使用ggplot / qplot来做到这一点?

Here is some example code: 这是一些示例代码:

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

Is this what you had in mind? 这是你的想法吗?

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)

This creates a separate data frame, centroids , with columns x , y , and class where x and y are the mean values by class. 这将创建一个单独的数据框, centroids ,列xyclass ,其中xy是按类的平均值。 Then we add a second point geometry layer using centroid as the dataset. 然后我们使用centroid作为数据集添加第二个点几何图层。

This is a slightly more interesting version, useful in cluster analysis. 这是一个稍微有趣的版本,在聚类分析中很有用。

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 Response to OP's comment. 编辑回应OP的评论。

Vertical and horizontal error bars can be added using geom_errorbar(...) and geom_errorbarh(...) . 可以使用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)

If you want to calculate, say, 95% confidence instead of std. 如果你想计算95%的置信度而不是std。 error, replace 错误,替换

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

with

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