如何在ggplot2中反转y轴的顺序

时间:2013-04-25 19:45:22

标签: r ggplot2

我有这个数据框y。我正在尝试使用ggplot创建热图。我想颠倒y轴的顺序。最高值应为00:00,值应减少到23:59。例如,最高值应该是00:00,然后是01:00,02:00,03:00等。现在,R轴从01:00开始,然后是02:00,03:00等任何想法我怎么能在ggplot2中做到这一点?

 cols<-c("white","#F0FFFF","#BBFFFF","#00FFFF","#42C0FB","#1C86EE", "green","yellow","#C9821E", "#FF0000", "#FF0000")
 vals<-c(0,0.19,0.29,0.39, 0.49,0.59, 0.69, 0.79, 0.89, 0.90,1)
 brk<-c(20, 30, 40, 50, 60, 70, 80, 90, 100)
 ggplot(y,aes(DATE, Time, fill=CPU)) + geom_tile() + theme_bw() 
    + scale_fill_gradientn(name="CPU Utilization", colours=cols, values=val, limits=c(0,100), breaks = brk)
     + guides(fill = guide_legend(keywidth = 5, keyheight = 1))+ scale_x_date(breaks = "1 days", labels=date_format("%a")) 
   + coord_trans(y="reverse")

\ n

 dput(head(y,50))
    structure(list(DATE = structure(c(15809, 15809, 15809, 15809, 
    15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 
    15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 
    15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 
    15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 
    15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 15809, 
    15809), class = "Date"), Time = c("20:14", "20:29", "20:44", 
    "20:59", "21:14", "21:29", "21:44", "21:59", "22:14", "22:29", 
    "22:44", "22:59", "23:14", "23:29", "23:44", "23:59", "00:14", 
    "00:29", "00:44", "00:59", "01:14", "01:29", "01:44", "01:59", 
    "02:14", "02:29", "02:44", "02:59", "03:14", "03:29", "03:44", 
    "03:59", "04:14", "04:29", "04:44", "04:59", "05:14", "05:29", 
    "05:44", "05:59", "06:14", "06:29", "06:44", "06:59", "07:14", 
    "07:29", "07:44", "07:59", "08:14", "08:29"), CPU = c(30, 30, 
    30, 31, 30, 27, 25, 23, 24, 22, 20, 21, 22, 21, 20, 20, 20, 15, 
    17, 15, 20, 16, 15, 16, 15, 14, 14, 11, 12, 11, 19, 22, 22, 21, 
    19, 20, 20, 17, 16, 10, 9, 9, 9, 10, 12, 13, 14, 14, 16, 16)), .Names = c("DATE", 
    "Time", "CPU"), row.names = 4205:4254, class = "data.frame")

1 个答案:

答案 0 :(得分:3)

由于ggplot2将您的y轴值转换为因子,因此只需提前将所有值转换为感兴趣的因子:

..

plot as shown