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

From: Bob Green <bgreen_at_dyson.brisnet.org.au>
Date: Fri, 13 Jun 2008 21:14:13 +1000

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)))



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Fri 13 Jun 2008 - 14:26:34 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 13 Jun 2008 - 15:00:39 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive