问题
I have created the below historgram using the plot function:
hist(mst$Total[which(mst$Total<100)], axes = TRUE, ylab = "", xlab = "", main = "", col = "chartreuse4", breaks = tb, freq=TRUE, right = FALSE)
The breaks have been specified as the following:
tb = c(0,1,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100)
I would like to be able to fill specific historgram bins with different colours.
colour one: [0,1)
colour two: [1,5)
colour three: [5,10) [10,15) and [15,20)
colour four: All bins from [20,25] onwards
How can I do this using r base package graphics?
Many thanks
Updated with accepted answer:
Using the accepted answer I was able to create the below plot:
range <- c(0, 1, 5, 20, 100)
col <- findInterval(tb, range, all.inside = TRUE)
col[which(col==1)] <- "firebrick1"
col[which(col==2)] <- "gold"
col[which(col==3)] <- "darkolivegreen1"
col[which(col==4)] <- "forestgreen"
hist(mst$Total[which(mst$Total<100)], axes = TRUE, ylab = "", xlab = "", main = "", col = col, breaks = tb, freq=TRUE, right = FALSE)
回答1:
First we define your color intervals
tb <- c(0,1,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100)
range <- c(0, 1, 5, 20, 100)
and then arrange your breaks
col <- findInterval(tb, range, all.inside = TRUE)
col
[1] 1 2 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
You can then use col
to color each bin
hist(mst$Total[which(mst$Total<100)], axes = TRUE, ylab = "", xlab = "", main = "", col = col, breaks = tb, freq=TRUE, right = FALSE)
Unfortunately I can't test it since you provided no data, but this should work.
来源:https://stackoverflow.com/questions/37086048/change-colour-of-specific-histogram-bins-in-r