在R和ggplot2中使用具有固定数量的facet的facet_wrap或facet_grid

时间:2018-03-06 09:41:22

标签: r ggplot2 facet-wrap facet-grid

我使用了Nsaunders'而是nice to follow approach of using facet_grid in ggplot2 for a gantt-style diagram

但是我遇到了问题。它是一个具有固定数量的房间的计划,数据来自SQL数据库。有些日子并非所有客房都预订。但我仍希望将它们作图。

所以这是我的情节代码

# The data
tasks <- data.frame(
task  = as.factor(dataset$NUMMER),
date  =  dataset$BEGINN,
start =dataset$BEGINN,
end = dataset$ENDE,
room = as.factor(dataset$RAUM))

# Names of the rooms
y_labels = c('1.01', '1.02', '1.03', '1.04', '1.05', '1.09', '1.11', '1.12', '1.13', '1.22')

# offset tasks in plot if > 1 per room
tasks$ymin <- c(rep(0, nrow(tasks)))
t <- table(tasks$room)
for(room in rownames(t)) {
   if(t[[room]] > 1) {
      ss <- tasks[tasks$room== room,]
      y  <- 0
      for(i in as.numeric(rownames(ss))) {
         tasks[i,]$ymin <- y
         y <- y + 1.2
      }
   }
}

# plot
library(ggplot2)
ggplot(tasks, aes(xmin = start.hour, xmax = end.hour, ymin = ymin, ymax = ymin + 1)) + 
        geom_rect(fill = tasks$fill) + 
        geom_text(aes(x = start.hour + 0.2, y = ymin +.5, label=task), hjust="left") +
        facet_wrap(~room, nrow=8, drop=FALSE, strip.position= "left", as.table=FALSE, scales="free_y") +
        xlim(7,22) +
        scale_y_discrete(breaks = y_labels, labels= y_labels) +
        scale_x_continuous(breaks=c(7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22), labels=c("7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00")) 

This leads to the following visualization 这很好。 But this is what I want it to look like

如果有人知道如何让所有房间都可见 - 即使他们今天没有价值,我也会非常高兴。 预先感谢您的帮助。

这将是一天的数据。正如你所看到的那样,房间没有价值&#34; 1.11&#34;和&#34; 1.22&#34;。但是我仍然希望绘制那些房间。

task = c("20181BTDS198401", "20181BTDT569202","20171BMQ1135404", "20181BTDM274201", "20171BTDG524192", "20171BTDT981303", "20181BTQ1135001", "20171BTDB253801", "20181DNMA894501","20181BTDK906502", "20181BTDK908902", "20181BMR2854901", "20181BTQ1184401")

date = c("2018-02-22", "2018-02-22", "2018-02-22", "2018-02-22", "2018-02-22", "2018-02-22", "2018-02-22", "2018-02-22","2018-02-22", "2018-02-22", "2018-02-22", "2018-02-22", "2018-02-22")

start = c("18:00:00", "08:30:00", "18:00:00", "09:00:00", "14:00:00", "08:30:00", "18:00:00", "17:30:00", "09:00:00", "16:30:00", "18:00:00", "08:30:00", "18:00:00")

end = c("20:30:00", "16:00:00", "20:30:00", "16:30:00", "20:40:00", "13:00:00", "20:30:00", "21:30:00", "15:20:00", "18:00:00", "19:40:00", "13:20:00", "20:30:00")

room = c("1.01", "1.02", "1.02", "1.03", "1.04", "1.05", "1.05", "1.09", "1.12", "1.12", "1.12", "1.13", "1.13")

0 个答案:

没有答案