Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change histogram bar colours greater than a certain value

Tags:

r

histogram

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.

like image 919
MattLBeck Avatar asked Aug 11 '11 14:08

MattLBeck


2 Answers

Fundamentally you want a logical selector on test not on the cuts.

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)

ggplot2 histo

like image 71
Ari B. Friedman Avatar answered Sep 27 '22 19:09

Ari B. Friedman


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.

like image 35
Richie Cotton Avatar answered Sep 27 '22 19:09

Richie Cotton