將sicdegpz分為“L”, “M”, “H”三組

library(WWGbook)
dat <- WWGbook::autism
Group <- with(dat, cut(sicdegp, ordered=T, breaks=c(0, 1, 2, 3), 
                           labels=c("L", "M", "H")))
dta <- cbind(dat, Group)

設立centered years變項

dta$center <- round((dta$age-mean(dta$age)),2)
head(dta)
##   age vsae sicdegp childid Group center
## 1   2    6       3       1     H  -3.77
## 2   3    7       3       1     H  -2.77
## 3   5   18       3       1     H  -0.77
## 4   9   25       3       1     H   3.23
## 5  13   27       3       1     H   7.23
## 6   2   17       3       3     H  -3.77

繪圖

library(ggplot2)

p0 <- ggplot(data=dta, aes(x=center, y=vsae)) + labs(x='Age (in years,centered)', y='VASE score') + 
geom_point(alpha = 0.5) + stat_smooth(data=dta, formula=y ~ x, method='lm', se=T) + 
  facet_wrap(. ~ Group, ncol=3) +
  geom_line(aes(group = childid), alpha = 0.4) + 
  #將childid變項相連
  scale_x_continuous(limits = c(-4, 7.5),
                     breaks = seq(-2.5, 5, 2.5))#定義x軸
  
p0
## Warning: Removed 2 rows containing non-finite values (stat_smooth).
## Warning: Removed 2 rows containing missing values (geom_point).
## Warning: Removed 1 row(s) containing missing values (geom_path).

設立year-2, Standard Error,mean變項

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
dta$year <- (dta$age-2)
dta.1 <- dta %>% group_by(year, Group) %>%
  summarize(mean=mean(vsae), se=sd(vsae)/sqrt(n()))
dta.1 <- na.omit(dta.1)
head(dta.1)
## # A tibble: 6 x 4
## # Groups:   year [3]
##    year Group  mean    se
##   <dbl> <ord> <dbl> <dbl>
## 1     0 L      7    0.387
## 2     0 M      8.67 0.435
## 3     0 H     12.4  0.542
## 4     1 M     14.1  0.775
## 5     1 H     21.2  1.52 
## 6     3 L     15.0  1.47

繪圖

p1 <- ggplot(data=dta.1) +
  aes(year, mean, group=Group, shape=Group) +
  geom_errorbar(aes(ymin=mean - se,
                    ymax=mean + se),
                width=.6, size=.6, 
                position=position_dodge(.5)) +
  geom_line(position=position_dodge(.5), 
            aes(linetype=Group))+##分類三條連線
  geom_point(position=position_dodge(.5), 
             size=rel(3))+##標示點點
  scale_shape_manual(values = c(1, 5, 10))+##更改圖例
  labs(x="Age (in year -2)", y="VSAE score")+
  theme(legend.position= c(0.07,0.85),)##更改圖例位置
  
  
p1