Saving your plot

You can save you plot with ggsave.

library(ggplot2)
ggsave("cars.pdf")
ggsave("cars.tiff")

The default is to save the last plot created in the format determined by the file extension at size of the current graphics device. You can adjust all these in the ggsave command. Look at the help file.

Grouping

In ggplot, group is another aesthetic. However any aesthetic that creates distinction between items will cause groups to occur:

library(ggplot2)
library(nlme)
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
ggplot(Oxboys,aes(age,height)) + geom_point() + geom_line(aes(group=Subject))

ggplot(Oxboys,aes(age,height)) + geom_point() + geom_line(aes(colour=Subject))

ggplot(Oxboys,aes(age,height)) + geom_point() + geom_line(aes(linetype=Subject))

Once the grouping is defined, it is in effect for all subsequent layers:

ggplot(mpg, aes(displ, cty, colour=drv)) +
  geom_point() +
  geom_smooth()
## `geom_smooth()` using method = 'loess'

We can add an overall best-fit line by redefining the group in the aesthetic for geom_smooth:

ggplot(mpg, aes(displ, cty, colour=drv)) +
  geom_point() +
  geom_smooth(aes(group=1))
## `geom_smooth()` using method = 'loess'

Exercise: Using the gapminder dataset (library(gapminder)), make a line graph of life expectancy of each country over time. Colour countries by the continent.