Change histogram bar colours greater than a certain value

混江龙づ霸主 提交于 2019-11-29 01:20:18

问题


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.


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/7027448/change-histogram-bar-colours-greater-than-a-certain-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!