-3

Is there a way to assign two different colours according to categorical values in rect graph??

rect(0, yb, Studies.sort,yt,col=("black","lightgray"[Area$"Theory"])

obviously.. this is wrong.....

Area consist of two categorical variables - "Theory" and "Vocational".

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • 1
    Your original data.frame would be helpful – MattLBeck Aug 23 '12 at 11:55
  • Welcome to Stack Overflow! If you made a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that demonstrates your question / problem, we would find it easier to answer. – Andrie Aug 23 '12 at 12:18

2 Answers2

4

You were close, the following works:

plot(1:10)
mydf <- data.frame( xl =1:5, yb=1:5, xr=2:6, yt=10:6, 
    group=sample( c('A','B'), 5, replace=TRUE) )
with(mydf, rect( xl, yb, xr, yt, col=c('black','grey')[group]) )

It is important that group here be a factor (not just a character vector). However if you use a named vector of the colors (with the names matching the group variable) then it would also work with a character vector.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110
2

You need to call rect for each colour that you want to draw, and have those colours in a categorical column in your data frame so that you can filter the data per category for each call to rect.

I don't know what your original data is like, so here's something similar:

# set up simple plotting window
plot.new()
plot.window(xlim=c(0,6),ylim=c(0,8))

# example data. Using colour as the categorical value we will filter on
sample.d <- data.frame(x=c(3,4,5,6), yb=c(1,3,5,7), yt=c(0,2,4,6),
colour=c("black","black","red","red"))

# draw black rectangles
black.d <- sample.d[sample.d$colour == "black",]
rect(0, black.d$yb, black.d$x, black.d$yt, col="black")

# draw red rectangles
red.d <- sample.d[sample.d$colour == "red",]
rect(0, red.d$yb, red.d$x, red.d$yt, col="red")
MattLBeck
  • 5,701
  • 7
  • 40
  • 56