[R] histogram with bars colored according to a vector of values

Jim Lemon jim at bitwrit.com.au
Fri Jul 26 07:55:56 CEST 2013


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



More information about the R-help mailing list