Skip to content

Instantly share code, notes, and snippets.

@cbrown5
Created October 28, 2020 10:55
Show Gist options
  • Save cbrown5/b4e36b8731dcd4c595e61f81967d0992 to your computer and use it in GitHub Desktop.
Save cbrown5/b4e36b8731dcd4c595e61f81967d0992 to your computer and use it in GitHub Desktop.
# How to ggplot2 efficiently
# CJ Brown 2020-10-27
library(ggplot2)
#
# Make some data
#
n <- 20 #Sample size per group
sd <- 5 #SD for errors
#All this is just to make some data, using
# a cubic regression equation
X <- cbind(rep(1, n), 1:n, (1:n)^2, (1:n)^3)
b <- matrix(c(-10, 0, 50,
1, 0.1, -1,
2, 0.4, -0.1,
-0.1, -0.01, 0), nrow = 4, byrow = T)
Y1 <- X %*% b[,1] + rnorm(n, sd = sd)
Y2 <- X %*% b[,2] + rnorm(n, sd = sd)
Y3 <- X %*% b[,3] + rnorm(n, sd = sd)
#Put data into a dataframe
dat <- data.frame(
yobs = c(Y1, Y2, Y3),
xvar = rep(1:n, 3),
grp = rep(LETTERS[1:3], each = n))
#
# Plot the data
#
#A base R plot, but fiddly to customize!
plot(dat$xvar, dat$yobs)
#A ggplot
#base of the plot , name the data
ggplot(dat) +
#add axes
aes(x = xvar, y = yobs, color = grp) +
#add data to axes (here points)
geom_point() +
#add a smoothing trend
stat_smooth(method = "gam",
formula = y ~ s(x, k = 4)) +
#individual panels for each group
facet_wrap(~grp) +
#change the theme (overall look)
theme_classic() +
#Modify the colour palette
scale_color_brewer(palette = "Dark2")
#colorbrewer2.org
#
# Making snippets
#
#Navigate to the menu bar then:
# Tools > Global Options > Code > 'edit snippets'
# (the button way down the bottom)
# Here's my snippet:
# snippet gg
# ggplot(${1:data}) +
# aes(x = ${2:x}, y = ${3:y}, color = NULL) +
# geom_${4:geomtype}()
#The ${1:data} etc... just
#once that's set up, type 'gg' and hit tab, away you go:
ggplot(data) +
aes(x = x, y = y, color = NULL) +
geom_geomtype()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment