我有很多数据可供人们接触细菌多达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是否有更优雅的方法?另外,如何更改图表顶部的框的外观?
答案 0 :(得分:2)
stat_summary
是不可选项,因为(请参见?stat_summary
):
stat_summary在唯一x
上运行
也就是说,尽管我们可以取y
的平均值,但是x
保持不变。但是我们可能会做其他非常简洁的事情:
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
elements。