[R] differentiate groups on barplot

Marc Schwartz marc_schwartz at comcast.net
Tue May 15 04:22:30 CEST 2007


On Tue, 2007-05-15 at 11:36 +1000, Murray Pung wrote:
> To differentiate between groups on the barplot, I guessed that col =
> colr[test$group] would have worked. How can I do this?
> 
> Many Thanks
> Murray
> 
> 
> test <-
> structure(list(patient = 1:20, score = c(100, 95, 80, 75,
> 64, 43, 42, 40, 37, 35, 30, 29, 27, 26, 23, 22, 19,
> 18, 17, 16), group = c(1, 0, 1, 0, 1, 0, 1, 0, 1,
> 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0)), .Names = c("patient",
> "score", "group"), class = "data.frame", row.names = 1:20)
> attach(test)
> 
> 
> colr <- c("gray","pink")
> barplot(score,beside = T,space = .4,col = colr[test$group])


R's indexing is 1 based, not 0 based.  Hence:

> colr[0]
character(0)

> colr[1]
[1] "gray"

> colr[2]
[1] "pink"


All you really need is:

  barplot(test$score, beside = TRUE, space = .4, col = colr)

as 'colr' will be recycled as required here.


HTH,

Marc Schwartz



More information about the R-help mailing list