使用非构面列(以及使用非构面列的标签)排列facet_grid

时间:2010-03-15 03:45:42

标签: r ggplot2 facet

我对ggplot2中的facetting有几个问题......

假设我有一个返回如下所示数据的查询:

(请注意,它按Rank asc排序,警报asc和两个警报的等级为3,因为他们的总计=第4周的1798,而Rank是根据第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

(下面的重复代码)

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) 

现在我这样做了......

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

我明白了......

alt text http://img101.imageshack.us/img101/9103/ss20100315112108.png

请注意,它根据警报进行了刻面,并且刻面按字母顺序排列。

两个问题:

  1. 如何通过闹钟保持其面貌,但以正确的顺序显示? (排名asc,警报asc)。
  2. alt text http://img17.imageshack.us/img17/6986/ss20100315113243.png

    1. 另外,如何通过闹钟保持它的分面,但是显示来自Rank而不是Alarm的标签?
    2. alt text http://img85.imageshack.us/img85/470/ss20100315113529.png

      请注意,我不能仅仅考虑Rank,因为ggplot2只能看到3个方面来绘制真正有4种不同警报的地方。

1 个答案:

答案 0 :(得分:6)

回答你的第一个问题:你可以简单地重新排序因子级别,使它们不再是按字母顺序排列的,如下所示:

spark$Alarm<-factor(spark$Alarm, levels(spark$Alarm)[c(1,4,2,3)])

对于第二个问题,您可以编写自己的贴标机功能,以便关联警报和等级,例如

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