[R] Switching the order of legend boxes in a lattice bar graph

Bob Green bgreen at dyson.brisnet.org.au
Fri Jun 13 13:14:13 CEST 2008


I suspect there is a simple solution to this problem, but have been 
unable to find it. Below is some code that I have run to create 3 
lattice graphs. I have been asked to change the legend so that the 
'No' and dark blue are above "Y" and light blue in the legend to 
mirror the stacked bars in the graph which feature dark blue above light blue.

I have tried changing the data as well as the order of the legend 
text, without success.  Any assistance is much appreciated,

regards

Bob Green



library(lattice)
SNFP1 <- as.table(matrix(c(4,1, 4,4, 1,3, 2,7, 1,6, 0,4), ncol = 6, 
dimnames = list(group=c("Y","No"), Status=c("A","B", "C", "D", "E", "F"))))
barplot(SNFP1, beside=FALSE, legend=TRUE, ylim=c(0, 60), ylab="N of 
patients", main ="district 1", col=c("light blue", "dark blue"))

# "A","B", "C", "D", "E", "F"

SNFP2 <- as.table(matrix(c(3,7, 1,5, 0,1, 0,1), ncol = 4, dimnames = 
list(group=c("Y","No"), Status=c("G","H", "I", "J"))))
barplot(SNFP2, beside=FALSE, legend=TRUE, ylim=c(0, 60), ylab="N of 
patients", main ="district 2", col=c("light blue", "dark blue"))

# "G", "H", "I", "J",

SNFP3 <- as.table(matrix(c(3,0, 0,2, 3,4), ncol = 3, dimnames = 
list(group=c("Y","No"), Status=c("K","L", "M"))))
barplot(SNFP3, beside=FALSE, legend=TRUE, ylim=c(0, 60), ylab="N of 
patients", main ="district 3", col=c("light blue", "dark blue"))


df1 <- as.data.frame(t(SNFP1))
df2 <- as.data.frame(t(SNFP2))
df3 <- as.data.frame(t(SNFP3))
stuff <- make.groups(A=df1, B=df2, C=df3)

# simple version
barchart(Freq ~ Status | which, groups=group, data=stuff, 
stack=TRUE,scales=list(x=list(relation="free")), auto.key=TRUE)

# advanced version
barchart(Freq ~ Status | which, groups=group, data=stuff, stack=TRUE, 
as.table=TRUE, layout=c(2,2), 
skip=c(F,T,F,F),scales=list(x=list(relation="free")), ylab="patients",
main="Figure 1: X by district", 
par.settings=list(superpose.polygon=list(col=c("light blue", "dark 
blue"))), auto.key=list(x = .6, y = .7, corner = c(0, 0)))



More information about the R-help mailing list