How to color a ggplot histogram differently based on precise cut off points?

前端 未结 1 1912
日久生厌
日久生厌 2021-01-27 13:23

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

相关标签:
1条回答
  • 2021-01-27 13:35

    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")
    

    0 讨论(0)
提交回复
热议问题