[R] Help with color coded bar graph
Marc Schwartz
marc_schwartz at comcast.net
Fri Sep 7 22:21:50 CEST 2007
On Fri, 2007-09-07 at 15:07 -0500, Marc Schwartz wrote:
> On Fri, 2007-09-07 at 12:45 -0700, 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.
> >
> > - Luis Naver
>
> How about this:
>
> barplot(rep(1, length(A)), col = "black", space = 0, border = 0)
>
> barplot(A, col = grey(0.9), space = 0, border = 0, add = TRUE)
>
> The first call sets the plot region to black, ensuring that the x and y
> axes are consistent with the second call.
>
> Alternatively, you can use barplot2() in the gplots CRAN package to do
> this in a single call, as it has an argument to color the plot region.
Actually, here is an easier way:
barplot(rep(1, length(A)),
col = ifelse(A == 0, "black", grey(0.9)), space = 0, border = 0)
Just set 'col' based upon the value in 'A'.
HTH,
Marc
More information about the R-help
mailing list