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
Try the lattice
lib:
library("lattice")
MyData <- as.data.frame(Titanic)
barchart(Freq ~ Survived | Age * Sex, groups = Class, data = MyData,
auto.key = list(points = FALSE, rectangles = TRUE, space
= "right", title = "Class", border = TRUE), xlab = "Survived",
ylim = c(0, 800))
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
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:
mydat <- cbind(rbind(a,b,0),rbind(0,0,c))[,c(1,6,2,7,3,8,4,9,5,10)]
barplot(mydat,space=c(.75,.25))
To see what's going on under the hood, take a look at mydat
:
> mydat
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
a 3 0 3 0 2 0 1 0 0 0
b 3 0 2 0 2 0 2 0 2 0
0 0 0 1 0 2 0 3 0 4
Here, you're plotting each bar with three values (the value of a
, the value of b
, the value of c
). Each column of the mydat
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.