【发布时间】:2019-01-07 22:05:51
【问题描述】:
我反复测量了雄性和雌性动物在四种不同生殖状态(处女、交配、怀孕和父母)下的特定行为。我想用以下方式表示我的数据(x:生殖状态,y:行为值):
- 具有相同行为值的点水平分布而不是重叠的点图
- 每个子组(例如处女男性)还应该有一个显示行为平均值的片段
- 每个个体动物也应该易于处理,用细线连接对应于每个生殖状态的个体的点
我已经成功完成了 1) 和 2),但无法将它们与我的 3)rd 目标结合起来。有人可以帮我吗?
这是一个例子:
library(ggplot2)
Function to obtain a mean segment for each group
MinMeanSEMMax <- function(x) {
v <- c(min(x), mean(x) - sd(x)/sqrt(length(x)), mean(x), mean(x) + sd(x)/sqrt(length(x)), max(x))
names(v) <- c("ymin", "lower", "middle", "upper", "ymax")
v
}
# Mock dataframe:
Sex<-rep(c("M","F"), times=12)
ID<-rep(seq(from=1, to=6), times=4)
Behavior<-rnorm(24, mean=10, sd=3)
State<-rep(c("virgin", "virgin", "mated", "mated", "expecting", "expecting", "parent", "parent"), times=3)
d<-data.frame(ID,Sex,Behavior,State)
# Prepare mean value for plotting of mean segments
g<-ggplot(d, aes(x=factor(State), y=Behavior, colour=Sex))+
stat_summary(fun.data=MinMeanSEMMax, geom="boxplot", position=position_dodge(), outlier.shape = 21, outlier.size = 3, size=1)+
scale_x_discrete(limits=c("virgin", "mated", "expecting", "parent"), labels=c("virgin"="Virgin", "mated"="Mated", "expecting"="Expecting", "parent"="Parent"))+
dat.g <- ggplot_build(g)$d[[1]]
g
# The plot
b<-ggplot(d, aes(x=factor(State), y=Behavior, colour=factor(Sex)))+
geom_segment(data=dat.g, aes(x=xmin, xend=xmax,y=middle, yend=middle), colour=c("blue3","brown2","blue3","brown2","blue3","brown2","blue3","brown2"), size=1)+
geom_dotplot(aes(fill=Sex),binaxis="y", stackdir="center", position=position_dodge(width=1), binwidth = 0.3)+
labs(x="",y="Behavior")+
theme_classic()+
theme(axis.line.x = element_line(color="black", size = 1),
axis.line.y = element_line(color="black", size = 1))+
theme(legend.position="none")+
theme(axis.text.x =element_text(size=10),axis.text.y=element_text(size=10), axis.title=element_text(size=11,face="bold"))+
scale_fill_manual(name="Sex", values=c("brown2", "blue3"), breaks=c("F", "M"))+
scale_colour_manual(name="Sex",values=c("brown2","blue3"),breaks=c("F", "M"),labels=c("Female", "Male"))+
scale_x_discrete(limits=c("virgin", "mated", "expecting", "parent"), labels=c("virgin"="Virgin", "mated"="Mated", "expecting"="Expecting", "parent"="Parent"))+
theme(text=element_text(family="serif"))
b
【问题讨论】:
标签: r ggplot2 grouping line boxplot