[R] assigning colors to barplot when beside=TRUE

Paul Murrell p.murrell at auckland.ac.nz
Thu Dec 4 23:45:06 CET 2003


Hi


Alejandro Munoz Del Rio wrote:
> 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 haven't figured out exactly what your code is supposed to produce, but 
I suspect that you are calculating colv incorrectly.  In your example, 
you get a colv with 5 elements.  There are a total of 10 bars plotted 
(some are zero height because the value they are plotting is NA).  The 
colours get applied to bars from left to right so in your case we get:

bar height:  7 NA  6 NA  1 NA NA  4 NA  3
bar colour:  2  3  2 NA NA  2  3  2 NA NA

(note that the colours are recycled).  I cannot yet suggest what the 
correct calculation of colv should be for your example, but the 
following colv setting would do the job in this case:

colv <- c(2, NA, 3, NA, 2, NA, NA, NA, NA, NA)

Now we get:

bar height:  7 NA  6 NA  1 NA NA  4 NA  3
bar colour:  2 NA  3 NA  2 NA NA NA NA NA

Hope that helps

Paul



> 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/
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help


-- 
Dr Paul Murrell
Department of Statistics
The University of Auckland
Private Bag 92019
Auckland
New Zealand
64 9 3737599 x85392
paul at stat.auckland.ac.nz
http://www.stat.auckland.ac.nz/~paul/




More information about the R-help mailing list