I would like to color a ggplot histogram by different vertical cutoff points. I was able to use this answer, but found that on my data the bins are split up and shortened. Minimal example and chart below.
How can I split up the bins vertically without getting these chopped up shorter bins?
library(tidyverse)
set.seed(42)
# define cutoffs
cutoff_1 <- -21
cutoff_2 <- 60
df <- data.frame(rand = rnorm(10000)*100) %>%
mutate(colors = case_when(
rand < cutoff_1 ~ "red",
rand >= cutoff_1 & rand <= cutoff_2 ~ "blue",
rand > cutoff_2 ~ "green"
)
)
n.bins <- 20 # number of bins
additional.cutoffs <- c(cutoff_1, cutoff_2) # additional bins
bins <- seq(min(df$rand), max(df$rand), length.out = n.bins)
bins <- c(bins, additional.cutoffs) %>% sort()
df %>%
ggplot(aes(x=rand, fill=colors)) +
geom_histogram(breaks=bins) +
geom_vline(xintercept=c(cutoff_1, cutoff_2), colour="black")