Skip to content

Instantly share code, notes, and snippets.

@dill
Last active October 14, 2015 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dill/4e971bd6c49f7544b998 to your computer and use it in GitHub Desktop.
Save dill/4e971bd6c49f7544b998 to your computer and use it in GitHub Desktop.
Comparison of plotting covariates against distance, base graphics vs. ggplot2
# plot of size versus distance and sea state versus distance
# w. linear model and LOESS smoother overlay
# base graphics
par(mfrow=c(1,2))
plot(distdata[c("size","distance")], xlab="Group size", ylab="Distance (m)",pch=19,col=rgb(0,0,0,0.4), cex=0.6)
# increase span from default 0.75 for slightly smoother curve
lo <- loess(distance ~ size, distdata, span=0.8)
lmm <- lm(distance ~ size, distdata)
preddat <- data.frame(size=seq(0,8,1))
lines(x=preddat$size, y=predict(lmm, preddat),lty=2)
lines(x=preddat$size, y=predict(lo, preddat))
plot(distdata[c("SeaState","distance")], xlab="Beaufort sea state", ylab="Distance (m)",pch=19,col=rgb(0,0,0,0.4), cex=0.6)
lo <- loess(distance ~ SeaState, distdata, span=0.8)
lmm <- lm(distance ~ SeaState, distdata)
preddat <- data.frame(SeaState=seq(0,8,1))
lines(x=preddat$SeaState, y=predict(lmm, preddat),lty=2)
lines(x=preddat$SeaState, y=predict(lo, preddat))
# plot of size versus distance and sea state versus distance
# w. linear model and LOESS smoother overlay
# ggplot2 graphics
library(reshape2)
library(ggplot2)
# extract the data we want and melt it into shape
distplot <- distdata[,c("distance","size","SeaState")]
names(distplot) <- c("Distance", "Size", "Beaufort")
distplot <- melt(distplot, id.vars="Distance", value.name="covariate")
# make the plot
p <- ggplot(distplot, aes(x=covariate, y=Distance)) +
geom_point() +
facet_wrap(~variable, scale="free") +
geom_smooth(method="loess") +
geom_smooth(method="lm") +
labs(x="Covariate value", y="Distance (m)")
print(p)
@dill
Copy link
Author

dill commented Oct 14, 2015

What they look like:

base graphics

ggplot2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment