So far, I've managed to change the colour a single bar in a histogram following the example here
test <- rnorm(100);
h <- hist(test);
b <- cut(1, h$breaks);
clr <- rep("grey", length(h$counts));
clr[b] <- "red";
plot(h, col=clr);
I want to be able to change the colour of histogram bins that are above a certain x-axis value - e.g. that are above 1 in the distribution function in the example. Part of the reason why I am having trouble is that I don't exactly understand the factor that cut()
returns.
Fundamentally you want a logical selector on test
not on the cut
s.
Here's what your cut object looks like:
> bks <- cut(test,10)
The levels are of type character:
levels(bks) 1 "(-2.53,-2.01]" "(-2.01,-1.5]" "(-1.5,-0.978]" "(-0.978,-0.459]" [5] "(-0.459,0.0596]" "(0.0596,0.578]" "(0.578,1.1]" "(1.1,1.62]"
[9] "(1.62,2.13]" "(2.13,2.65]"
The data is of type numeric:
> head(as.numeric(bks))
[1] 5 6 6 6 3 5
Here's a solution using ggplot2 rather than making the cuts and so forth by hand:
test <- rnorm(100)
dat <- data.frame( x=test, above=test>1 )
library(ggplot2)
qplot(x,data=dat,geom="histogram",fill=above)
Change your colour vector, clr
, so that it shows red whenever the bar is greater than 1 and grey otherwise.
clr <- ifelse(h$breaks < 1, "grey", "red")[-length(h$breaks)]
Then plot as before.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With