Skip to content

Instantly share code, notes, and snippets.

@erictleung

erictleung/corr_plots.R

Last active Jul 10, 2020
Embed
What would you like to do?
Plot examples of varying strengths of correlation
# Load libraries
library(ggplot2)
library(patchwork)
set.seed(20200616)
# Create data
n_pts <- 20
x <- round(runif(n_pts) * 10, 1)
# Construct example correlations
perf_pos <- data.frame(x = x, y = x)
high_pos <- data.frame(x = x, y = x + runif(n_pts, 0, 4))
low_pos <- data.frame(x = x, y = x + runif(n_pts, 0, 10))
no_corr <- expand.grid(x = 1:10, y = 1:10) + runif(100)
low_neg <- data.frame(x = x, y = -x + runif(n_pts, 0, 10))
high_neg <- data.frame(x = x, y = -x + runif(n_pts, 0, 4))
perf_neg <- data.frame(x = x, y = -x)
# Create functiont to help plot
pp <- function(x, t) {
ggplot(x, aes(x, y)) +
geom_point(size = 3) +
ggtitle(t) +
theme_minimal() +
theme(axis.text.x = element_blank(), axis.text.y = element_blank())
}
# Plot dimensions
h <- 2.35
# Positive examples with actual axes
plot_spacer() +
pp(low_pos, "") + xlab("Amount of food eaten") + ylab("Feeling of being full") +
plot_spacer()
ggsave("pos_plot.png", width = 3*h, height = h)
# Negative examples with actual axes
plot_spacer() +
pp(low_neg, "") + xlab("Speed of car") + ylab("Total travel time") +
plot_spacer()
ggsave("neg_plot.png", width = 3*h, height = h)
# No correlation example with actual axes
plot_spacer() +
pp(no_corr, "") + xlab("Weight gain") + ylab("Test scores") +
plot_spacer()
ggsave("non_plot.png", width = 3*h, height = h)
# Plot positive correlations
pp(low_pos, "Low positive (r = 0.5)") +
pp(high_pos, "High positive (r = 0.9)") +
pp(perf_pos, "Perfect positive (r = 1.0)")
ggsave("positive_plots.png", width = 3*h, height = h)
# No correlation
plot_spacer() +
pp(no_corr, "No correlation") +
plot_spacer()
ggsave("no_corr_plot.png", width = 3*h, height = h)
# Plot negative correlations
pp(low_neg, "Low negative (r = -0.5)") +
pp(high_neg, "High negative (r = -0.9)") +
pp(perf_neg, "Perfect negative (r = -1.0)")
ggsave("negative_plots.png", width = 3*h, height = h)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.