################################################################### ## R Programming Session 6 ################################################################## ## Section 1.2 - Intro to plotting x <- 1:10 y <- 3*x^2 - 2*x plot(y) # Plots against 1:length(y) plot(x,y) plot(list(x=x, y=y)) # Remember what a \$ sign means for a list plot(cbind(x, y)) plot(cos, -2*pi, 2*pi) xy <- data.frame(a=x, b=y) plot(b ~ a, data=xy) # Types of plots plot(x, y, type='p') plot(x, y, type='l') plot(x, y, type='b') plot(x, y, type='o') plot(x, y, type='h') plot(x, y, type='s') # Changing the plotting character plot(x, y, pch = 19) plot(x, y, pch = "+") # Changing the line type plot(x, y, type ='l', lty = 2) # Axis labels plot(x, y, type = 'l', xlab = "My x-axis", ylab = "A function", xlim = c(0,8), ylim = c(-30,120), main = "A useless title") # Adding another line to your plot z <- -2*x^2 + 4*x + 80 lines(x, z, col = "green", lty = 4) # Adding a legend to tell people what they are seeing legend(0, 115, legend = c("Function 1", "Function 2"), col = c("black", "green"), lty = c(1,4)) # Multiple plots par(mfrow = c(2,1)) plot(x, y, type = "l") plot(x, z, type = "l", col = "green") # Adding math text par(mfrow = c(1,1)) plot(x, y, type = "l", xlab = expression(theta), ylab = expression(3*theta^2 - 2*theta)) ### Section 2 - Saving your plot directly # Changing the plotting window size x11(width = 6, height = 4) plot(x, y, type = "l", xlab = expression(theta), ylab = expression(3*theta^2 - 2*theta)) # Saving it as pdf without using the viewer window (useful if you want to specify the plotting size) # Make sure the scale you choose is such that the text/labels you add are readable pdf("Myfirstplot.pdf", width = 6, height = 4) plot(x, y, type = "l", xlab = expression(theta), ylab = expression(3*theta^2 - 2*theta)) dev.off() ## Section 3 A full example looking at the brain and body weights of some animals library(MASS) ?Animals Animals plot(brain ~ body, data = Animals, pch = 19) pdf("BrainBodyRegression.pdf", width = 8, height = 6) plot(log(brain) ~ log(body), data = Animals, ylim = c(0,10), ylab = "Log brainweight (g)", xlab = "Log bodyweight (kg)", main = "Body and brainweights for 28 species of animal", pch = 19) abline(lm(log(brain) ~ log(body), data = Animals)) #identify(log(Animals\$body), log(Animals\$brain), labels = row.names(Animals)) Dino <- c(6,16,26) text(log(Animals\$body)[Dino], log(Animals\$brain)[Dino], labels = row.names(Animals)[Dino], pos = 2) ModernAnimals <- Animals[-Dino,] abline(lm(log(brain) ~ log(body), data = ModernAnimals), col = "red", lty = 2) legend("topleft", legend = c("All Animals", "Modern Animals"), lty = c(1,2), col = c("black", "red")) dev.off()