且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

清晰标记水平barplot / geom_segment上的时间等级数据

更新时间:2023-12-03 10:42:40

The issue is, I think, linked to the fact that the times class appears to be holding durations rather than times of day (though I cannot actually find the documentation on the class, having never used it before). Because that format is not explicitly handled by ggplot it is being converted to numeric for plotting (you can see the stored numeric values in your output from dput).

While there is likely a better solution involving converting to POSIX or storing the values directly as time of day, you can accomplish your immediate goal by simply multiplying the numeric value (which is fraction of a day) by 24 to get the time. Then, set sensible axis breaks and add labels as desired, like so:

ggplot(BedMap) +
  geom_segment(aes(x = 0, #start of light grey bar, indicates bed occupied & discharge planning has not yet started
                   y = RoomBed, 
                   xend = 24*DcOrderTime, #end of light grey bar
                   yend = RoomBed), 
               color = "Light Grey", 
               size = 6) +
  geom_segment(aes(x = 24*DcOrderTime, #start of dark grey bar, indicates bed still occupied but discharge planning has begun
                   y = RoomBed, 
                   xend = 24*DcTime, #end of dark grey bar, indicates patient has been discharged, bed is unoccupied
                   yend = RoomBed), 
               color = "Dark Grey", 
               size = 6) +
  geom_segment(aes(x = 24*DepartTime, #start of blue bar, indicates new patient has been placed in bed
                   y = RoomBed, 
                   xend = 24, #end of blue bar (set at midnight/end of day)
                   yend = RoomBed), 
               color = "Blue", 
               size = 6) +
  geom_point(aes(x = 24*DecisionTime, 
                 y = RoomBed), 
             color = "black", size = 3) +
  geom_point(aes(x = 24*RequestBedTime, 
                 y = RoomBed), 
             color = "green", size = 3) +
  theme(legend.position = "none") +
  labs(x = "Time", y = "Room-Bed", title = "Daily Bed Map") +
  scale_x_continuous(breaks = seq(0, 24, 3)
                     , labels = sprintf("%02d:00",seq(0, 24, 3))
                     )

Which gives

The builtin in scale_x_time does not appear to work here, and that is part of what leads me to suspsect that the times class holds durations rather than times of day. If you are using this format often, it may be worthwhile to instead write your own transformation/scale function to use repeatedly.