Skip to content

Instantly share code, notes, and snippets.

@jonesor
Created November 9, 2018 13:18
Show Gist options
  • Save jonesor/6b7e70f0eebdc3d660058fa66353a9fe to your computer and use it in GitHub Desktop.
Save jonesor/6b7e70f0eebdc3d660058fa66353a9fe to your computer and use it in GitHub Desktop.
Overlaying histograms and density plots in R (base and ggplot2)
#I first simulate a dataset to use for this example
set.seed(123)
years <- 2013:2015
n <- 100
df1 <- data.frame(year = rep(years, each = n),
eggdate = c(rnorm(n, 40, 4),
rnorm(n, 45, 5),
rnorm(n, 67, 7)))
#Make sure year is coded as a "factor"
df1$year <- as.factor(df1$year)
#For colour "hex codes" see:
#https://www.rapidtables.com/web/color/html-color-codes.html
#BASE R method
hist(df1$eggdate[df1$year == 2013], xlim = c(0, 100), ylim = c(0, 50), col = "#FF634780", breaks = 10)
hist(df1$eggdate[df1$year == 2014], add = T, col = "#228B2280", breaks = 10)
hist(df1$eggdate[df1$year == 2015], add = T, col = "#1E90FF80", breaks = 10)
#ggplot method (first load the library)
library(ggplot2)
#THe basic plot information (does not plot anything yet)
A <- ggplot(data = df1, aes(eggdate, fill = year))
#Make a plot - histogram
A + geom_histogram(alpha = 0.6, position = "identity")
#It is probably better to use density rather than histogram, particularly when
#there are different sample sizes in different groups
A + geom_density(alpha = 0.6, position = "identity")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment