# Plots
# There are two types of plots in R. The first are the old-school kind
# The basic command is plot()
# Learn by doing
x <- rnorm(100)
y <- rnorm(100)
z <- c(rep(seq(1, 2, 1), 50))
a <- c(rep(1, 33), rep(2, 33), rep(3, 34))
plot(x, y)
# Arguments: xlab = xlabel
# ylab = ylabel
# main = main title
# pch = plot character
# lwd = point/line thickness
# lty = line type
# xlim = x limit
# ylim = y limit
# col = color (can be called by number or name: http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf)
plot(x, y, pch = 2)
# Differentiate? Of course
plot(x, y, pch = z)
plot(x, y, pch = z, col = z)
plot(x, y, pch = z, col = a)
# Draw lines?
time <- seq(1990, 2017, 1)
y.time <- rnorm(length(time))
z.time <- rnorm(length(time), 1)
plot(time, y.time, type = "l")
# Fully customizable
plot(time, y.time, type = "l", axes = F, xlab = "Year", ylab = "Amount",
lwd = 3, lty = 2)
axis(side = 1, at = c(1995, 2005, 2015), labels = c(1995, 2005, 2015))
axis(side = 2)
plot(time, y.time, type = "l", axes = F, xlab = "Year", ylab = "Amount",
lwd = 3, lty = 2)
lines(time, z.time)
# Oops!
plot(time, y.time, type = "l", xlab = "Year", ylab = "Amount",
lwd = 3, lty = 2, ylim = c(min(y.time), max(z.time)))
lines(time, z.time, lwd = 3, lty = 3)
legend(2010, 4, c("Y", "Z"), lty = c(2, 3), lwd = 3)
# PDF!
pdf("/Users/scj0014/Myfiles/Teaching/Extra lab sessions/figure.pdf",
width = 6, height = 5)
plot(time, y.time, type = "l", xlab = "Year", ylab = "Amount",
lwd = 3, lty = 2, ylim = c(min(y.time), max(z.time)))
lines(time, z.time, lwd = 3, lty = 3)
legend(2010, 4, c("Y", "Z"), lty = c(2, 3), lwd = 3)
dev.off()
# Multiple plots?
par(mfrow = c(2, 2))
plot(mtcars$wt, mtcars$mpg, main = "Scatterplot of wt vs. mpg")
plot(mtcars$wt, mtcars$disp, main = "Scatterplot of wt vs. disp")
hist(wt, main = "Histogram of wt")
boxplot(wt, main = "Boxplot of wt")
# Another is ggplot
library(ggplot2)
# Totally different syntax. ggplot2 deals with data frames
# Learn by reading: http://tutorials.iq.harvard.edu/R/Rgraphics/Rgraphics.html
# http://stats.idre.ucla.edu/r/seminars/ggplot2_intro/
mtcars
p1 <- ggplot(data = mtcars, aes(x = wt, y = mpg))
p1 + geom_point()
# We can add a model
predictions <- predict(lm(mtcars$mpg ~ mtcars$wt))
p1 + geom_point() + geom_line(aes(y = predictions))
# Smoother?
p1 + geom_point() + geom_smooth()
# Can we add more aesthetics? Definitely
p1 + geom_point(aes(col = cyl)) + geom_smooth()
# A lot of old commands
p1 + geom_point(aes(pch = cyl)) + geom_smooth()
# What failed?
p1 + geom_point(aes(pch = as.factor(cyl))) + geom_smooth()
p1 + geom_point() + facet_wrap(~as.factor(cyl))