[R] assigning colors to barplot when beside=TRUE

Alejandro Munoz Del Rio munoz at cs.wisc.edu
Thu Dec 4 21:37:40 CET 2003


dear list,

i am having trouble coloring the bars in a barplot. my data have two
groups, which i would like to plot side by side. within each group i
want to sort the observations in decreasing order, like a pareto
chart. the bar colors would relfect the value of a third variable.

below i have generated a reproducible example. the bar heights are a
given pig's "gain", "type" identifies groups, and the color depends
on "day".

i would expect to get the five bars colored red, green, red, followed
by two whites. instead, i see: red red white red white. (i am aware
that in the code below "colv", the color vector, contains NAs, but
that does not seem to be the source of the problem).

i would be grateful for any help. 

alejandro

# pigs.dat
pig type day gain 
1   1    1   1
2   1    1   6
10  1    3   7
a   B    NA  3
b   B    NA  4

pigs <- read.table("~/pigs.dat", h=TRUE)
attach(pigs)
tbl <- tapply(gain, list(type=="B", pig), I)	# generate matrix
o1 <- rev(order(tbl[1, 1:3]))		# sort order for group 1
oB <- rev(order(tbl[1, 4:5]))+3		# ditto, group B
oday <- day[match(levels(pig), pig)]	# day of sacrifice ordered as pig/tbl
colv <- match(oday, c(1, 3))+1
barplot(tbl[,c(o1, oB)], beside=TRUE, ylim=c(0,8), xlab="pig", 
                ylab="weight gain (g)", col=colv)
   legend(12, 8, fill=c(2:3,NA), legend=c(paste("day", c(1,3)), "uninjured"))
   box()
detach()
rm(pigs, tbl, o1, oB, oday, colv)



-------------------------------------------------
This mail sent through IMP: http://horde.org/imp/




More information about the R-help mailing list