Created
January 14, 2020 21:53
-
-
Save nikosbosse/ec90911f601d4af955ab5abc768568cc to your computer and use it in GitHub Desktop.
plot_two_histograms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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