Cleared outputs, set some init cells
[ou-jupyter-r-demo.git] / plot_extensions.R
1 # Multiple plot function
2 #
3 # ggplot objects can be passed in ..., or to plotlist (as a list of ggplot objects)
4 # - cols: Number of columns in layout
5 # - layout: A matrix specifying the layout. If present, 'cols' is ignored.
6 #
7 # If the layout is something like matrix(c(1,2,3,3), nrow=2, byrow=TRUE),
8 # then plot 1 will go in the upper left, 2 will go in the upper right, and
9 # 3 will go all the way across the bottom.
10 #
11 multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
12 library(grid)
13
14 # Make a list from the ... arguments and plotlist
15 plots <- c(list(...), plotlist)
16
17 numPlots = length(plots)
18
19 # If layout is NULL, then use 'cols' to determine layout
20 if (is.null(layout)) {
21 # Make the panel
22 # ncol: Number of columns of plots
23 # nrow: Number of rows needed, calculated from # of cols
24 layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
25 ncol = cols, nrow = ceiling(numPlots/cols))
26 }
27
28 if (numPlots==1) {
29 print(plots[[1]])
30
31 } else {
32 # Set up the page
33 grid.newpage()
34 pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
35
36 # Make each plot, in the correct location
37 for (i in 1:numPlots) {
38 # Get the i,j matrix positions of the regions that contain this subplot
39 matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
40
41 print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
42 layout.pos.col = matchidx$col))
43 }
44 }
45 }
46
47 # From https://sejohnston.com/2012/08/09/a-quick-and-easy-function-to-plot-lm-results-in-r/
48 ggplotRegression <- function (fit) {
49
50 require(ggplot2)
51
52 ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) +
53 geom_point() +
54 geom_smooth(method = "lm", col = "red") +
55 labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
56 "Intercept =",signif(fit$coef[[1]],5 ),
57 " Slope =",signif(fit$coef[[2]], 5),
58 " P =",signif(summary(fit)$coef[2,4], 5))) +
59 theme(plot.title = element_text(size=12))
60 }