Plotting group mean responses

## for plotting
library(ggplot2)
## for data
library(nlme)
## Load data
data(BodyWeight)
## Check data
head(BodyWeight)
## Grouped Data: weight ~ Time | Rat
##   weight Time Rat Diet
## 1    240    1   1    1
## 2    250    8   1    1
## 3    255   15   1    1
## 4    260   22   1    1
## 5    262   29   1    1
## 6    258   36   1    1

basePlot <- ggplot(data = BodyWeight, mapping = aes(x = Time, y = weight, group = Rat))

## Scatter plot and line plot
basePlot + layer(geom = "point") + layer(geom = "line")

plot of chunk unnamed-chunk-1


## Add color to the line plot only
basePlot + layer(geom = "point") + layer(geom = "line", mapping = aes(color = Diet))

plot of chunk unnamed-chunk-1


## Means over time
library(dplyr)
## 
## Attaching package: 'dplyr'
## 
## The following object is masked from 'package:nlme':
## 
##     collapse
## 
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## 
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
BWSummary <- BodyWeight %.% group_by(Diet, Time) %.% summarise(mean_weight = mean(weight))

## Add summary statistics to graph
basePlot + layer(geom = "point") + layer(geom = "line", mapping = aes(color = Diet)) + 
    layer(data = BWSummary, geom = "line", mapping = aes(y = mean_weight, group = Diet))

plot of chunk unnamed-chunk-1


## Color for mean responses
basePlot + layer(geom = "point") + layer(geom = "line", mapping = aes(color = Diet)) + 
    layer(data = BWSummary, geom = "line", mapping = aes(y = mean_weight, group = Diet, 
        color = Diet))

plot of chunk unnamed-chunk-1


## Using constant to specify thickness (size) and transparency (alpha)
completePlot <- basePlot + layer(geom = "point") + layer(geom = "line", mapping = aes(color = Diet)) + 
    layer(data = BWSummary, geom = "line", mapping = aes(y = mean_weight, group = Diet, 
        color = Diet), size = 2, alpha = 0.3)
completePlot

plot of chunk unnamed-chunk-1


## White background
completePlot + theme_bw()

plot of chunk unnamed-chunk-1