ggplot2 is an great package for making pretty plots.
This notebook will only descripe ggplot2 very shortly, as there are other excellent resources descibing the details:
Cheatsheet - 2-page pdf with a summary of ggplot2:
# Load ggplot2
library(ggplot2)
# Data
data(mtcars)
The backbone is created with the ggplot function, where we input our data.frame:
ggplot(mtcars)
Usually we would also add the aesthetics (aes), which tells which variables should be on the x-axes, on the y-axis, and if any variables should be used to indicate color, shape, or linetype.
ggplot(mtcars, aes(x = hp, y = disp, color = gear))
This however does not draw the plot. We need to add geometrics (geom), which tells ggplot2 how to plot the data:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
geom_point()
We can then add a theme:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
geom_point() +
theme_bw()
We can add scales:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
geom_point() +
theme_bw() +
scale_x_continuous(name="HP", breaks=seq(0,350,50))
We can add labels:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
geom_point() +
theme_bw() +
scale_x_continuous(name="HP", breaks=seq(0,350,50)) +
ylab("New label") +
ggtitle("My title")
We can facet the plot, by splitting it by a variable:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
geom_point() +
theme_bw() +
scale_x_continuous(name="HP", breaks=seq(0,350,50)) +
ylab("New label") +
ggtitle("My title") +
facet_grid(.~cyl)
We can add a linear regression:
ggplot(mtcars, aes(x = hp, y = disp, color = gear)) +
geom_point() +
theme_bw() +
scale_x_continuous(name="HP", breaks=seq(0,350,50)) +
ylab("New label") +
ggtitle("My title") +
facet_grid(.~cyl) +
stat_smooth(method = "lm")