[R] Help with color coded bar graph

Jim Lemon jim at bitwrit.com.au
Sat Sep 8 12:58:18 CEST 2007


Luis Naver wrote:
> I have a list of observations that are -1, 1 or 0.  I would like to  
> represent them in a horizontal bar color coded based on value like a  
> stacked bar graph. I can achieve this in the form of a png with the  
> following code:
> 
> A = floor(runif(10)*3) - 1
> 
> png(width=100, height=10)
> par(mar=c(0,0,0,0))
> image(matrix(A), col=grey(c(0.1, 0.5, 0.9)))
> dev.off()
> 
> However I would like to do this with one of the standard plotting  
> tools (i.e. barplot) to take advantage of labels and multiple  
> series.  Any help would be appreciated.
> 
Hi Luis,
I understood your request as wanting a single horizontal bar with 10 
segments, each colored according to the value of A. If this is correct, 
you might want:

library(plotrix)
plot(1,xlim=c(-1,1),ylim=c(-1,1),xlab="",ylab="",type="n",axes=FALSE)
gradient.rect(-1,-0.1,1,0.1,col=grey(c(0.1,0.5,0.9))[A+2])

Jim



More information about the R-help mailing list