## Model II linear regressions with legend for SES
# With ideas borrowed from https://stackoverflow.com/questions/6103288/reduced-major-axis-line-and-ci-for-ggplot-in-r

## Libraries
library(ggplot2)
library(lmodel2)

## Data and Regressions
# So we get the same random numbers each time
set.seed(123) 
# Make data
dat <- data.frame(x = runif(20, 0, 10), y = runif(20, 0, 10))
# Model the data and save results as mod
mod <- lmodel2(y ~ x, data=dat, "interval", "interval", 99)

## Get Coefficients
# Only want the results of the regressions saved as reg
reg <- mod$regression.results
# Rename columns in reg so they're easy to use
names(reg) <- c("method", "intercept", "slope", "angle", "p-value")
# Check that the regressions look like so we know what will be plots
print(reg)
##   method intercept     slope    angle p-value
## 1    OLS 4.3234303 0.2621199 14.68793    0.13
## 2     MA 1.7165344 0.7354053 36.33096    0.13
## 3    SMA 0.7299905 0.9145136 42.44334      NA
## 4    RMA 2.2128445 0.6452995 32.83413    0.13
## Plot
# Specifying the data as dat for the points and reg for the lines
ggplot() + 
  geom_point(data = dat, aes(x, y)) +
  geom_abline(data = reg, aes(intercept = intercept, slope = slope, colour = method), show_guide = TRUE)

## Plot with only one line
# Can do this by subsetting
ggplot() + 
  geom_point(data = dat, aes(x, y)) +
  geom_abline(data = subset(reg, method == "MA"), aes(intercept = intercept, slope = slope, colour = method), show_guide = TRUE)