Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
plot_two_histograms
plot_two_histograms <- function(vector1, vector2,
breaks = 100,
upper_limit = NA,
...){
if(!is.na(upper_limit)){
vector1 <- vector1[vector1 < upper_limit]
vector2 <- vector2[vector2 < upper_limit]
}
## set breakpoints and define minimum
## breakpoint a and maximum breakpoint b
a <- min(c(vector1, vector2))
b <- max(c(vector1, vector2))
## define axis
ax <- pretty(a:b, n = breaks)
while(min(ax) > a | max(ax) < b){
if (min(ax) > a){
a <- a - (ax[2] - ax[1])
}
if (max(ax) < b){
b <- b + (ax[2] - ax[1])
}
ax <- pretty(a:b, n = breaks)
}
## make histogram 1 and 2
plot1 <- hist(vector1, breaks = ax, plot = FALSE)
plot2 <- hist(vector2, breaks = ax, plot = FALSE)
## define two colors
col1 <- rgb(168,209,225,max = 255, alpha = 75)
col2 <- rgb(248,183,193, max = 255, alpha = 75)
## plot and add 2nd plot to first
plot(plot1, col = col1, ...)
plot(plot2, col = col2, add = TRUE)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment