2016-10-14 46 views
0

我想繪製ggplot中兩個子集的框圖的迴歸線。然而它看起來不可能。ggplot2框圖中子集的迴歸線

這裏是dataframe

下面是代碼:

ggplot(VMT,aes(x=size , y=vmt, group=specimen,colour=sex,fill=sex)) + 
geom_boxplot()+ 
scale_colour_brewer(palette="Set1")+ 
#geom_point()+ 
ylab("VTM (°C)")+ 
xlab("size")+ 
geom_smooth(data=subset(VMT,sex==F), 
      aes(mean(size),mean(vmt),  group=specimen,color=sex,method=lm,se=FALSE)) 

回答

2

這是你想要的嗎?看看這個問題,您似乎想要對每個標本採用sizevmt的平均值,並使用這些值進行線性迴歸。這是使用dplyr包完成的。

library(ggplot2) 
library(dplyr) 
## df is same as VMT 
df <- read.csv("uro7.csv")[,1:7] 
df2 <- filter(df, sex == "F") %>% 
    group_by(specimen) %>% 
    select(-one_of(c("date", "time", "sex", "turn"))) %>% 
    summarize_all(mean) 

Select下降四列和summarize_all需要的sizevmt平均值。由於這保留了列名,aes(x = size, y = vmt)可以包含在ggplot中,因此它可以傳遞給geom_boxplotgeom_smooth。另一方面,aes(group = specimen, colour = sex, fill = sex)需要爲geom_boxplot,因爲df2沒有這些列。

ggplot(df,aes(x=size, y=vmt)) + 
    geom_boxplot(aes(group=specimen,colour=sex,fill=sex))+ 
    scale_colour_brewer(palette="Set1")+ 
    #geom_point()+ 
    ylab("VTM (°C)")+ 
    xlab("size") + 
    geom_smooth(data=df2, 
     col = "red", method = lm, se = FALSE) 

enter image description here

此外,關於原代碼的一些意見:

你應該有sex == "F"method = lm, se = FALSE不應該(兩人都被定格在我的代碼)包含在aes