简体   繁体   中英

ggplot change order of continuous y axis values

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

在此处输入图片说明

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?

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()

在此处输入图片说明

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.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM