Skip to content

Instantly share code, notes, and snippets.

@soumyaray
Created April 28, 2018 07:00
Show Gist options
  • Save soumyaray/2b17dd609c2ce92f96e70d8f17c2fb02 to your computer and use it in GitHub Desktop.
Save soumyaray/2b17dd609c2ce92f96e70d8f17c2fb02 to your computer and use it in GitHub Desktop.
Interactive and standalone regression plotting
# plot_regr_rsq(points) plots points and regression
#
# You can supply the following parameter:
# points - dataframe of x,y points to plot
plot_regr_rsq <- function(points) {
if (nrow(points) == 0) {
plot(NA, xlim=c(-5,50), ylim=c(-5,50), xlab="x", ylab="y")
return()
}
plot(points, xlim=c(-5,50), ylim=c(-5,50), pch=19, cex=2, col="gray")
if (nrow(points) < 2) return()
regr <- lm(points$y ~ points$x)
regr_summary <- summary(regr)
abline(regr, lwd=2, col="cornflowerblue")
text(1, 50, paste(c("Raw intercept: ", round(regr$coefficients[1], 2)), collapse=" "), cex=0.80)
text(1, 45, paste(c("Raw slope : ", round(regr$coefficients[2], 2)), collapse=" "), cex=0.80)
text(1, 40, paste(c("Correlation : ", round(cor(points$x, points$y), 2)), collapse=" "), cex=0.80)
text(1, 35, paste(c("R-squared : ", round(regr_summary$r.squared, 2)), collapse=" "), cex=0.80)
}
# interactive_regression() runs a regression simulation.
# Click on the plotting area to add points and see a corresponding regression line
# (hitting ESC will stop the simulation).
#
# You can supply the following parameter:
# old_pts - dataframe of x,y points to start interacting with
#
# You will also see three numbers:
# intercept – where the regression line intercepts the y-axis
# regression coefficient – the slope of x on y
# correlation - correlation of x and y
# r-squared - R^2 of y
interactive_regression_rsq <- function(points=data.frame()) {
cat("Click on the plot to create data points; hit [esc] to stop")
repeat {
plot_regr_rsq(points)
click_loc <- locator(1)
if (is.null(click_loc)) break
if(nrow(points) == 0 ) {
points <- data.frame(x=click_loc$x, y=click_loc$y)
} else {
points <- rbind(points, c(click_loc$x, click_loc$y))
}
}
return(points)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment