开发者

Change histogram bar colours greater than a certain value

So far, I've managed to change the colour a single bar in a histogram following the example her开发者_如何学Ce

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

Change histogram bar colours greater than a certain value


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜