Arrange facet_grid by non-facet column (and labels using non-facet column)
I have a couple of questions regarding facetting in ggplot2...
Let's say I have a query that returns data that looks like this:
(note that it's ordered by Rank asc, Alarm asc and two Alarms have a Rank of 3 because their Totals = 1798 for Week 4, and Rank is set acc开发者_如何学编程ording to Total for Week 4)
Rank Week Alarm Total
1 1 BELTWEIGHER HIGH HIGH 1000
1 2 BELTWEIGHER HIGH HIGH 1050
1 3 BELTWEIGHER HIGH HIGH 900
1 4 BELTWEIGHER HIGH HIGH 1800
2 1 MICROWAVE LHS 200
2 2 MICROWAVE LHS 1200
2 3 MICROWAVE LHS 400
2 4 MICROWAVE LHS 1799
3 1 HI PRESS FILTER 2 CLOG SW 1250
3 2 HI PRESS FILTER 2 CLOG SW 1640
3 3 HI PRESS FILTER 2 CLOG SW 1000
3 4 HI PRESS FILTER 2 CLOG SW 1798
3 1 LOW PRESS FILTER 2 CLOG SW 800
3 2 LOW PRESS FILTER 2 CLOG SW 1200
3 3 LOW PRESS FILTER 2 CLOG SW 800
3 4 LOW PRESS FILTER 2 CLOG SW 1798
(duplication code below)
Rank = c(rep(1,4),rep(2,4),rep(3,8))
Week = c(rep(1:4,4))
Total = c( 1000,1050,900,1800,
200,1200,400,1799,
1250,1640,1000,1798,
800,1200,800,1798)
Alarm = c(rep("BELTWEIGHER HIGH HIGH",4),
rep("MICROWAVE LHS",4),
rep("HI PRESS FILTER 2 CLOG SW",4),
rep("LOW PRESS FILTER 2 CLOG SW",4))
spark <- data.frame(Rank, Week, Alarm, Total)
Now when I do this...
s <- ggplot(spark, aes(Week, Total)) +
opts(
panel.background = theme_rect(size = 1, colour = "lightgray"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
axis.line = theme_blank(),
axis.text.x = theme_blank(),
axis.text.y = theme_blank(),
axis.title.x = theme_blank(),
axis.title.y = theme_blank(),
axis.ticks = theme_blank(),
strip.background = theme_blank(),
strip.text.y = theme_text(size = 7, colour = "red", angle = 0)
)
s + facet_grid(Alarm ~ .) + geom_line()
I get this....
alt text http://img101.imageshack.us/img101/9103/ss20100315112108.png
Notice that it's facetted according to Alarm and that the facets are arranged alphabetically.
Two Questions:
- How can I can I keep it facetted by alarm but displayed in the correct order? (Rank asc, Alarm asc).
alt text http://img17.imageshack.us/img17/6986/ss20100315113243.png
- Also, how can I keep it facetted by Alarm but show labels from Rank instead of Alarm?
alt text http://img85.imageshack.us/img85/470/ss20100315113529.png
Note that I can't just facet on Rank because ggplot2 would see only 3 facets to plot where there are really 4 different Alarms.
To answer your first question: you could simply reorder factor levels so that they are no longer alphabetical, like so:
spark$Alarm<-factor(spark$Alarm, levels(spark$Alarm)[c(1,4,2,3)])
For the second question, you could write your own labeller function so associate Alarms and Ranks, something like
lbl.fn <- function(variable, value) { paste(spark$Rank[which(as.character(spark$Alarm)==as.character(value))],as.character(value)) }
s + facet_grid(Alarm ~ ., labeller="lbl.fn") + geom_line()
精彩评论