2

I am trying to plot shift data by hour (integer) ordered by 3 different shifts worked (8-16, 16-24, 24-8) by day as the x-axis. The hours I have are 24hr format and I want to plot them not in numerical order (0-24) but by the shift order (8-16, 16-24, 24-8).

Here is the code to create the data and make the plot. I want to put the 0-8 chunk above the 16-24 chunk.

set.seed(123)
Hour = sample(0:24, 500, replace=T)
Day = sample(0:1, 500, replace=T)

dat <- as.tibble(cbind(Hour, Day)) %>%
        mutate(Day = factor(ifelse(Day == 0, "Mon", "Tues")),
               Shift = cut(Hour, 3, labels = c("0-8", "8-16", "16-24")),
               Exposure = factor(sample(0:1, 500, replace=T)))

ggplot(dat, aes(x = Day, y = Hour)) +
        geom_jitter(aes(color = Exposure, shape = Exposure)) + 
        geom_hline(yintercept = 8) + 
        geom_hline(yintercept = 16) + 
        theme_classic()

Current plot

enter image description here

It is an interesting problem, and I have tried recoding a new hour variable that is in the order that I want but then I'm not sure how to plot it displaying the standard 24hr variable.

How would i accomplish this ordering?

QHarr
  • 83,427
  • 12
  • 54
  • 101
Curtis
  • 159
  • 7

2 Answers2

2

Not sure if I completely understand, but if you facet your table on the Shift column, it should do what you want. First you must factor the Shift column to the order you specify:


dat$Shift <- factor(dat$Shift, levels = c("0-8", "16-24", "8-16"))

ggplot(dat, aes(x = Day, y = Hour)) +
  geom_jitter(aes(color = Exposure, shape = Exposure)) + 
  facet_grid(Shift ~ ., scales = "free") +
  theme_classic()

enter image description here

Ryan
  • 281
  • 3
  • 12
  • I had not thought about faceting it by shift! Good idea, thank you! I wanted to be able to keep the hour axis, which is why I do not want to just plot it by shift. – Curtis Dec 23 '17 at 20:41
1
set.seed(123)
Hour = sample(0:24, 500, replace=T)
Day = sample(0:1, 500, replace=T)

dat <- as.tibble(cbind(Hour, Day)) %>%
  mutate(Day = factor(ifelse(Day == 0, "Mon", "Tues")),
         Shift = cut(Hour, 3, labels = c("0-8", "8-16", "16-24")),
         Exposure = factor(sample(0:1, 500, replace=T)))

dat$Shift <- factor(dat$Shift, levels=rev(levels(dat$Shift)))

ggplot(dat, aes(x = Day, y = Shift)) +
  geom_jitter(aes(color = Exposure, shape = Exposure)) + 
  geom_hline(yintercept = 8) + 
  geom_hline(yintercept = 16) + 
  theme_classic()

You just need to reverse the level.

enter image description here

Sixiang.Hu
  • 1,009
  • 10
  • 21