Plotting with ggplot
#good soure:
#plot stuff: http://www.statmethods.net/graphs/
#graphical parameters: http://www.statmethods.net/advgraphs/parameters.html
#data
Orange
#we're going to add a randomly assigned plot for each tree - aka a treatment
Orange$rando = round(rnorm(nrow(Orange), 2, 1))
#basic plot
plot(age ~ circumference, Orange, col = Tree, cex = 2, pch = 19)
mod <- lm (age ~ circumference, Orange)
abline(mod)
####plotting with ggplot ####
library(ggplot2)
#basic plot
basicgg <- qplot(y = age, x = circumference, data = Orange, color = Tree, size = 2, facets = rando~.)
basicgg
#fancier!
basicgg +
theme_bw()
#adding a line is harder here, so lets use the full ggplot function
#ggplot site: http://docs.ggplot2.org/0.9.2.1/ggplot.html
gplot <- ggplot(data = Orange, aes(x = circumference, y = age))
gplot+
geom_point(aes(color = Tree, size = 2)) +
geom_abline(intercept = coef(mod)["(Intercept)"], slope = coef(mod)["circumference"]) +
theme_bw() +
facet_grid(facets = rando~.) #following up on the question about the "tilda dot": you need the tilda to tell facet what to facet by. If you put the tilda first, the facets will be vertical. if you put it afterwards, they will be horizaontal, but you need the dot to imply that it is only one variable you are using. The dot is implied when the tilda is first.
####lets add the equation and R2 value for the line ####
#To do this, there are many, many ways. See this page for some examples: http://stackoverflow.com/questions/7549694/ggplot2-adding-regression-line-equation-and-r2-on-graph
#I am going to do a method that is applicable to facets and uses a modified code for the pre-existing ggplot function "stat_smooth()"
#first, we need to enable R to modify packages functions using devtools
library(devtools)
#now we get the modified function.
#we need to also install the packages that this modified function requires. For me, this was jsonlite - it will probably vary for you. Make sure to look at the text of the erro rmessages.
#This function creates its own regression line, and can fit a number of models. See more info here: https://gist.github.com/kdauria/524eade46135f6348140
source_gist("524eade46135f6348140", filename = "ggplot_smooth_func.R")
#now to do the plot
#because geom_smooth() makes its own line, we are going to remove the geom_abline() term and replace it with state_smooth_func() and geom_smooth(). These two lines together 1) define a liner model and 2) apply it to the graph
gplot+
geom_point(aes(color = Tree, size = 2)) +
theme_bw() +
stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE) +
geom_smooth(method="lm",se=FALSE) +
facet_grid(rando~.)