0

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)

enter image description here

arvi1000
  • 9,393
  • 2
  • 42
  • 52
Elizabeth
  • 39
  • 2
  • the answer like ggplot(dd,ases(x=t_in_day,y=y))+... would not help. This is a complete program, so you could run it before giving your answer. Thank you very much. – Elizabeth Apr 06 '18 at 23:01
  • Why do you have 48 hours? – Tung Apr 06 '18 at 23:29
  • Because I want to compare the day and the previous day data horizontally and vertically. That is what a actogram looks like. Thanks – Elizabeth Apr 07 '18 at 08:57
  • 1
    I figured out. dd1<-cbind(dd,col1) ggplot(dd1,aes(x=t_in_day,y=dd[,y],fill=col)) + geom_bar(stat="identity") + ...... – Elizabeth Apr 10 '18 at 21:05

0 Answers0