我想做一些类似日历图的事情,但是一个月多几个小时(而不是一年多几天)。我设法用 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)
Run Code Online (Sandbox Code Playgroud)
)
这只是一个例子来说明我的问题。正如您所看到的,日期本身是正确的(12 月 1 日是星期四,12 月 31 日是星期六),但数据填写错误(垂直而不是水平)。
我究竟做错了什么?
相反,它可能更容易使用facet_grid
。
另外,按名称引用变量!所以test
不用dat[2]
.
如果您不知道变量名称并且需要以编程方式设置它,请使用aes_string
或aes_
。
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())
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
341 次 |
最近记录: |