geom_line连接不同箱形图组的平均值(位置标识)

时间:2018-02-15 15:17:30

标签: r ggplot2

我想绘制一个geom_line,并连接不同组(侧面)内每个单盒图的平均值。请参阅下面的代码

df<-data.frame(time=as.factor(c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3)), 
               value=as.numeric(c(12, 8,17,13,12, 9, 10, 12, 9, 11, 10.5, 11.4, 10.9,15,7, 11.6, 12, 13)), 
               side=as.factor(c("E","Z","E","Z","E","Z","E","Z","E","Z","E","Z","E","Z","E","Z","E","Z")))

df2 <- ddply(df,.(time,side),summarise, val = mean(value))

ggplot(df, aes(x=factor(time), y=value, colour=side))+
geom_point(position="identity",aes(group=side), colour="black")+
geom_boxplot(color="black", position = "identity", aes(fill=side))+
scale_fill_manual(values=c("#999999", "#E69F00"))+
  geom_line(data = df2, aes(y = val, group = val)) 

1 个答案:

答案 0 :(得分:1)

您必须按side分组,而不是val分组。

ggplot(df, aes(x=factor(time), y=value, colour=side))+
  geom_point(position="identity",aes(group=side), colour="black")+
  geom_boxplot(color="black", position = "identity", aes(fill=side))+
  scale_fill_manual(values=c("#999999", "#E69F00"))+
  geom_line(data = df2, aes(time, val, group = side))