2017-10-20 46 views
1

我想做一些类似日历图的事情,但是要花费一个多月的时间(而不是一年的时间)。我设法用ggplot来做到这一点,但数据以错误的顺序填充。ggplot以错误的顺序填写数据

我做了这个可重放的例子:

library(ggplot2) 
library(scales) 
device <- "test" 
dat <- data.frame(matrix(nrow=31*24, ncol=2)) 
dat[,1] <- seq.POSIXt(from=(as.POSIXct("2016-12-01 00:00:00")), length.out=(31*24), by="1 hour") 
dat[,2] <- seq(from=1, to=nrow(dat), by=1) 
colnames(dat) <- c("Zeit", device) 

dat$month<-as.numeric(as.POSIXlt(dat$Zeit)$mon+1) 
dat$monthf<-factor(dat$month) 
dat$monthf<-factor(dat$month,levels=as.character(1:12),labels=c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),ordered=TRUE) 

dat$week <- as.numeric(format(dat$Zeit,"%W")) 

dat$weekday = as.POSIXlt(dat$Zeit)$wday 
dat$weekdayf<-factor(dat$weekday,levels=(c(1:6,0)),labels=(c("Mon","Tue","Wed","Thu","Fri","Sat","Sun")),ordered=TRUE) 

dat$day <- as.numeric(format(dat$Zeit,"%d")) 
dat$dayf<-factor(dat$day) 

dat$hour <- as.numeric(format(dat$Zeit,"%H")) 
dat$hourf<-factor(dat$hour) 

plot(ggplot(dat, aes(hourf, week, fill = dat[2])) + 
    scale_y_reverse() + 
    geom_tile(colour = "white") + 
    facet_wrap(monthf~weekdayf, ncol=7) + 
    scale_fill_gradientn(colours=c("darkgreen", "green", "yellow", "red","darkred"), 
               values=rescale(c(0, 0.25, 0.5, 0.75, 1)), 
               guide="colorbar") + 
    xlab("") + ylab("") + ggtitle(device) 

这只是为了显示我的问题的例子。正如你所看到的那样,这些日子本身是正确的(12月第一个星期四,12月31日是星期六),但是数据被错误地填充(垂直而非horicontally)。

我在做什么错?

Here you can see the result

+2

当使用'ggplot()'函数,你应该只是他们的名字引用您的列 - repalce'补= DAT [2]'和'补= test'。 –

回答

5

它可能更容易使用facet_grid代替。

另外,请参考变量的名称!所以使用test而不是dat[2]

如果您不知道变量名称并需要对其进行编程设置,请改为使用aes_stringaes_

ggplot(dat, aes(hourf, 1, fill = test)) + 
    geom_tile(colour = "white") + 
    facet_grid(week~monthf+weekdayf, switch = 'y') + 
    scale_fill_gradientn(colours=c("darkgreen", "green", "yellow", "red","darkred"), 
         values=rescale(c(0, 0.25, 0.5, 0.75, 1)), 
         guide="colorbar") + 
    xlab("") + ylab("") + 
    ggtitle(device) + 
    theme(axis.ticks.y = element_blank(), axis.text.y = element_blank()) 

enter image description here