# A variety of common graphics options/parameters library(faraway) # Basic scatterplot plot(math ~ read, hsb) # Titles, axis labels, tickmarks plot(math ~ read, hsb, main="Reading and Math") plot(math ~ read, hsb, ylab="Math Score") plot(math ~ read, hsb, xaxp=c(25, 75, 10)) # Notice that if you ask for tick marks beyond the plotting area # they are silently omitted (no error or warning) # Jitter plot(jitter(math) ~ jitter(read), data=hsb, main="Jittered Scores", ylab="Math", xlab="Reading") # not shown here: you can specify the amount of jitter # Marker color and symbol - specified numerically or as a character string plot(math ~ read, hsb, col="red") plot(math ~ read, hsb, col=1) plot(math ~ read, hsb, pch=15) plot(math ~ read, hsb, pch="a") # these are vector-valued parameters, so they can be # used to identify groups or create patterns plot(math ~ read, data=hsb, col=prog, pch=19) # here, prog is a vector (factor) coerced to numeric values # You get more control by explicitly building a factor of color names dot.color <- ifelse(hsb$prog=="academic", "blue", "red") dot.color[hsb$prog == "vocation"] <- "black" plot(math ~ read, data=hsb, col=dot.color, pch=19) # similarly with symbols, you can build your own vector # You can also control the default sequence of colors with palette() palette(c("blue","red","black")) plot(math ~ read, data=hsb, col=prog, pch=19) palette("default") # Overlaying graphical elements # You'll want to add a legend to the previous plot legend("bottomright", legend=levels(hsb$prog), fill=c("blue", "red", "black")) # overlay horizontal or vertical reference lines abline(h=mean(hsb$math)) #overlay a regression line plot(math ~ read, data=hsb, col=dot.color, pch=19) fit <- lm(math ~ read, data=hsb) abline(coef(fit)) abline(fit) # an arbitrary line in intercept-slope form abline(0, 1, col="red") # Multiple plots in one device opar <- par(mfrow=c(2,2)) for (i in 1:3) { plot(math ~ read, data=hsb, subset=(prog==levels(prog)[i]), main=levels(prog)[i], xlim=c(30,75), ylim=c(30,75)) abline(h=mean(hsb$math[hsb$prog==levels(hsb$prog)[i]])) abline(v=mean(hsb$read[hsb$prog==levels(hsb$prog)[i]])) } par(opar) library(lattice) xyplot(math ~ read | prog, data=hsb) xyplot(math ~ read | prog+gender, data=hsb, panel=function(x, y){ panel.xyplot(x, y) panel.lmline(x, y) }) library(ggplot2) qplot(read, math, data=hsb, facets=~prog+gender) + geom_smooth(method="lm") opar <- par(mfrow=c(2,2)) for (i in 1:3) { plot(math ~ read, data=hsb, subset=(prog==levels(prog)[i]), main=levels(prog)[i], xlim=c(30,75), ylim=c(30,75), pch=16) fit <- lm(math ~ read, data=hsb, subset=(prog==levels(prog)[i])) abline(coef(fit)) } par(opar)