john d
2013-Jul-26 02:13 UTC
[R] histogram with bars colored according to a vector of values
Dear all, Let's say I have the following data.frame: dat<-data.frame(x=rnorm(100), y=rnorm(100,2)) and I plot a histogram of variable x, somethink like: hist(dat$x, breaks=-5:5) Now, I'd like to color each bar according to the mean of the cases according to y. For instance, the color of the bar between -2 and -1 should reflect the mean of variable y for the corresponding cases. Any suggestions? John [[alternative HTML version deleted]]
Jim Lemon
2013-Jul-26 05:55 UTC
[R] histogram with bars colored according to a vector of values
On 07/26/2013 12:13 PM, john d wrote:> Dear all, > > Let's say I have the following data.frame: > > dat<-data.frame(x=rnorm(100), y=rnorm(100,2)) > > and I plot a histogram of variable x, somethink like: > hist(dat$x, breaks=-5:5) > > Now, I'd like to color each bar according to the mean of the cases > according to y. For instance, the color of the bar between -2 and -1 should > reflect the mean of variable y for the corresponding cases. Any suggestions? > > John >Hi John, Try this: dat$xcut<-cut(dat$x,breaks=-5:5) library(plotrix) barcol<-color.scale(by(dat$y,dat$xcut,mean),extremes=c("red","blue")) hist(dat$x,breaks=-5:5,col=barcol) Jim