I've encountered a small problem when creating a bar plot in R. There are 3 variables:
a <- c(3,3,2,1,0)
b <- c(3,2,2,2,2)
c <- 0:4
The bar plot should be grouped by 'a' and 'c', and 'b' should be stacked on top of 'a'. Doing the grouping and stacking seperately is straightforward:
barplot(rbind(a,c), beside=TRUE)
barplot(rbind(a,b), beside=FALSE)
How can you do both at once in one graph?
Doing this requires thinking about how
barplot
draws stacked bars. Basically, you need to feed it some data with 0 values in appropriate places. With your data:To see what's going on under the hood, take a look at
mydat
:Here, you're plotting each bar with three values (the value of
a
, the value ofb
, the value ofc
). Each column of themydat
matrix is a bar, sorted so that the ab bars are appropriately interspersed with the c bars. You may want to play around with spacing and color.Apparently versions of this have been discussed on R-help various times without great solutions, so hopefully this is helpful.
Try the
lattice
lib:As you can see the grouping and ploting is done at once.
Please also see: https://stat.ethz.ch/pipermail/r-help/2004-June/053216.html