如果我对某些间隔有0个计数,则drop = FALSE对geom_tile不起作用

时间:2018-04-11 16:38:34

标签: r ggplot2 data.table

以下代码首先生成一些虚拟数据,这些值可能不属于我设置的所有间隔。换句话说,某些间隔有一些0计数。当谈到绘制ggplot geom_tile时,每件事都是乱七八糟的。我使用scale_fill_manual(values=rev(rbPal(break1)), labels=rev(cuts),drop=FALSE),其中drop = FALSE应该解决问题,但事实并非如此。此代码是您可以在计算机上尝试的完整程序。

library(data.table)
library(ggplot2)
# we build some dummy data to table dt$y, total data contains n=15*24+3
set.seed(1)
n= 15*24 + 3
dt <- data.table(t=0:(n-1))
dt[, y := c(rep(c(1,2,3),times=5*24),9,9,9)]

# create t_in_day,day in table dt, which we will use them to locate x and y later
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)]

dd[, day_str := as.ordered(day)]
dd[, day_str := ordered(day_str,levels=rev(levels(day_str)))]

#create 10 different color panels and assign user defined intervals to corresponding colors
rbPal <- colorRampPalette(c("white","green"))
breakvect<-seq(0,10,by=1)
break1<-(length(breakvect)-1)
dd[,col1 := rbPal(break1)[as.numeric(cut(dd[,y],breaks = breakvect))]]

#label and store the intervals in cuts
cuts<-levels(cut(dd[,y],breaks = breakvect))
cuts<-gsub(","," - ",cuts)
cuts<-gsub("\\(","[",cuts)

#check the data I generated first fall to how many intervals defined by the user
print(length(unique(col1)))
print(dd)
#the graph are not created successfully even when we use drop=FALSE, everything is in a mess
ggplot(dd,aes(t_in_day,y=day_str,fill=col1)) + 
geom_tile(aes(fill=col1))+ 
scale_x_continuous(name="time (h)",breaks = 0:(8 * 6)) +
scale_y_discrete(name="starting day") + # scale_fill_gradient(low = "white", high = "limegreen")
scale_fill_manual(values=rev(rbPal(break1)),labels=rev(cuts),drop=FALSE)

0 个答案:

没有答案