Skip to content

Instantly share code, notes, and snippets.

@valentinitnelav
Created November 24, 2017 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valentinitnelav/98c043660515c2ca9316f53da8407d42 to your computer and use it in GitHub Desktop.
Save valentinitnelav/98c043660515c2ca9316f53da8407d42 to your computer and use it in GitHub Desktop.
plot confidence intervals for linear model with ggplot using geom_smooth
#####################################################
# CI-s for linear model with ggplot
#####################################################
library(ggplot2)
# -------------------------------------
# Use simulated data from Mick Wu
# -------------------------------------
set.seed(1)
dat4 <- data.frame(density=rlnorm(n=600, meanlog=5,sdlog=0.5),
area=rep(c("forest","grass","coast"),each=200),
region=rep(c("north","south"),300),
popul=rpois(n=600,lambda=1000)^2)
dat4$density <- dat4$density + as.numeric(dat4$area)*20 + as.numeric(dat4$region)*10
dat4$density <- dat4$density * rescale(dat4$popul^2,to=c(0.25,1))
# -------------------------------------
# Plot
# -------------------------------------
ggplot(data = dat4,
aes(x = popul,
y = density)) +
geom_point(shape = 21) + # add the points
geom_smooth(method='lm') + # add the fit line and CI-s
theme_bw() # optional; sets a black-white theme
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment