ggplot改变连续y轴值的顺序

时间:2017-12-22 17:37:48

标签: r ggplot2 dplyr jitter

我正在尝试按小时(整数)绘制按小时(整数)排序​​的班次数据,按天计算3个不同的班次(8-16,16-24,24-8)作为x轴。我的时间是24小时格式,我想不是按照数字顺序(0-24)绘制它们,而是按顺序(8-16,16-24,24-8)绘制它们。

以下是创建数据和制作图表的代码。我想将0-8块放在16-24块之上。

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

当前情节

enter image description here

这是一个有趣的问题,我尝试按照我想要的顺序重新编码一个新的小时变量但是我不确定如何绘制它显示标准的24小时变量。

我如何完成此排序?

2 个答案:

答案 0 :(得分:2)

不确定我是否完全理解,但是如果你在Shift列上面对你的表,它应该做你想要的。首先,您必须将Shift列计入您指定的顺序:


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

答案 1 :(得分: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()

你只需要扭转关卡。

enter image description here