I want to draw an colored actogram with a barplot shape for each data point. I use day or day_str to count the number of day, and use t_in_day to locate the hour within a day. I use facet_grid to let data from different days to show in different panels. But when I run my program, the data does not show in the right order. The data with the same day_str does not show in the same row, rather some of them appeared quite a few days latter. How to fix it? Thank you very much.
library(ggplot2)
library(data.table)
set.seed(123)
n= 15*24 + 3
dt <- data.table(t=0:(n-1))
dt[, y := abs(sin(2*pi*t/25.4)) + rnorm(n,1,0.2)]
dt[,t_in_day := t%%24]
dt[,day := (floor(t/24)+1)]
dt2 <- copy(dt)
dt2[,day := day-1]
dt2[,t_in_day := t_in_day + 24]
dt <- dt[day<max(day)]
dd <- rbind(dt, dt2)
dd <- dd[day>0]
dd[, day_str := sprintf("day\n%03d",day)]
col1<-c()
break1=10
rbPal <- colorRampPalette(c('red','yellow'))
col1 <- rbPal(break1)[as.numeric(cut(dd[,y],breaks = break1))]
cuts<-levels(cut(dd[,y],breaks = break1))
cuts<-gsub(","," - ",cuts)
cuts<-gsub("\\(","[",cuts)
ggplot(dd,aes(x=t_in_day,y=dd[,y])) +
geom_bar(stat="identity",aes(fill=col1)) +
facet_grid(day_str ~ .) + scale_x_continuous(name="time (h)",breaks = waiver())+
scale_y_continuous(name="y")+#scale_colour_gradient(low="red", high="yellow")+
scale_fill_manual(values=rbPal(break1),labels=cuts)