Partially color histogram in R

前端 未结 4 1962
慢半拍i
慢半拍i 2020-12-05 00:51

\"enter

I have a histogram as shown in the picture. I want the bars in the two regions

4条回答
  •  执念已碎
    2020-12-05 01:29

    I was using @Thomas' solution for years before I noticed that it's imprecise.

    In the example below I am following the accepted answer.

    fake_data <- c(0.35, 0.41, 0.41, 0.49, 0.49, 0.49, 0.51, 0.51, 0.59, 0.64, 0.7)
    
    fake_hist <- hist(fake_data, plot = F)
    fake_cuts <- cut(fake_hist$breaks, c(-Inf, 0.5, Inf))
    
    plot(fake_hist, col = fake_cuts)
    

    [wrong_hist][1]

    The cut is intended at 0.5, but the third bar is black, although it should be red. The reason is, that breaks contain all the boundaries including the left boundary of the first bar, meaning there are n+1 values, where n is the number of bars in the histogram. For colouring of n bars, one needs only the right boundaries and therefore we must exclude the first value.

    fake_data <- c(0.35, 0.41, 0.41, 0.49, 0.49, 0.49, 0.51, 0.51, 0.59, 0.64, 0.7)
    
    fake_hist <- hist(fake_data, plot = F)
    fake_cuts <- cut(fake_hist$breaks[-1], c(-Inf, 0.5, Inf))
    
    plot(fake_hist, col = fake_cuts)
    

    correct_hist

    Produces the colour split where expected.

    I am posting it here because it took me so long to find that there is a problem.

提交回复
热议问题