首页 > 解决方案 > 散点图中每个因素的统计摘要 ggplot2:fun.x、fun_y 组合怎么样?

问题描述

我有一堆关于人们接触细菌最多 5 次的数据。我正在比较戴手套和不戴手套的拾取量。我想通过因子 NumberContacts 绘制平均值并将其涂成红色。例如下图中的红点。 在此处输入图像描述

到目前为止,我有:

require(tidyverse)
require(reshape2)

做一些数据

    df<-data.frame(Yes=rnorm(n=100),
No=rnorm(n=100),
NumberContacts=factor(rep(1:5, each=20)))

计算每个组的平均值 = NumberContacts

centroids<-aggregate(data=melt(df,id.vars ="NumberContacts"),value~NumberContacts+variable,mean)

把它们分成两列

centYes<-subset(centroids, variable=="Yes",select=c("NumberContacts","value"))
centNo<-subset(centroids, variable=="No",select="value")
centroids<-cbind(centYes,centNo)
colnames(centroids)<-c("NumberContacts","Gloved","Ungloved")

制作一个丑陋的情节。

ggplot(df,aes(x=gloves,y=ungloved)+
  geom_point()+
  geom_abline(slope=1,linetype=2)+
  stat_ellipse(type="norm",linetype=2,level=0.975)+
  geom_point(data=centroids,size=5,color='red')+
  #stat_summary(fun.y="mean",colour="red")+ doesn't work
  facet_wrap(~NumberContacts,nrow=2)+
  theme_classic()

在此处输入图像描述

使用 stat_summary 有没有更优雅的方法?另外,如何更改图表顶部框的外观?

标签: rggplot2

解决方案


stat_summary不是一个选项,因为(参见?stat_summary):

stat_summary 对唯一的 x进行操作

也就是说,虽然我们可以取 的平均值yx但仍然是固定的。但是我们可以做一些其他非常简洁的事情:

ggplot(df, aes(x = Yes, y = No, group = NumberContacts)) +
  geom_point() + geom_abline(slope = 1, linetype = 2)+
  stat_ellipse(type = "norm", linetype = 2, level = 0.975)+
  geom_point(data = df %>% group_by(NumberContacts) %>% summarise_all(mean), size = 5, color = "red")+ 
  facet_wrap(~ NumberContacts, nrow = 2) + theme_classic() + 
  theme(strip.background = element_rect(fill = "black"),
        strip.text = element_text(color = "white"))

在此处输入图像描述

这也表明要修改上面的框,您要strip 查看theme.


推荐阅读