I\'m trying to color a ggplot histogram differently based on precise boundaries along the x axis. However, the colors are not accurate because a bin that contains values from bo
Maybe this'll work for you. You can specify the bin-breaks in geom_histogram. So we first create an evenly spaced bin-vector and add some cutoff points to it:
n.bins <- 5 # number of bins
additional.cutoffs <- c(3.9, 2.9) # additional bins
bins <- seq(min(mtcars$wt), max(mtcars$wt), length.out = n.bins)
bins <- c(bins, additional.cutoffs) %>% sort()
mtcars %>%
mutate(wt_color = ifelse(wt < cutoff_point, "red", "blue")) %>%
select(wt, wt_color) %>%
ggplot(aes(x=wt, fill = wt_color)) +
geom_histogram(breaks = bins) +
geom_vline(xintercept=additional.cutoffs, colour="black")