在ggplot中对y轴标签进行排序

时间:2017-12-08 12:29:06

标签: r ggplot2

我在两个数据框中有一个传记数据集:

library(tidyverse)
# dataframe of one-time ovents
one_timers <-
  tribble(~event, ~date,
          "birth", as.Date("1984/02/10"),
          "first toy", as.Date("1984/02/11"),
          "first kiss", as.Date("1992/05/15"),
          "moved out", as.Date("2003/08/29"),
          "first car", as.Date("2002/04/11"),
          "job", as.Date("2000/02/10"))
#dataframe of repeating events, say switchingt between companies that provide internet
sequence <-
  tribble(~event, ~from, ~to,  ~quality,
          "job", as.Date("2000/02/10"), as.Date("2000/02/17"), 2,
          "job", as.Date("2001/05/15"), as.Date("2001/06/10"), 4,
          "job", as.Date("2003/08/29"), as.Date("2004/02/10"), 5,
          "job", as.Date("2004/04/11"), as.Date("2005/01/10"), 10)

我想要创建这些事件的情节:

# plotting events
one_timers %>% 
  ggplot(aes(x = date, y = event)) +
  geom_point()

结果是:

plot with wrong chronology

这个情节没问题,但是我希望事件按时间顺序排序,所以我将event变量转换为因子日期根据日期重新排序:

one_timers <-
  one_timers %>% 
  mutate(event = event %>% as.factor() %>% forcats::fct_reorder(date))
levels(one_timers$event)
# and it works
one_timers %>% 
  ggplot(aes(x = date, y = event)) +
  geom_point()

plot with fixed chronology

但是现在让我们使用额外的图层来复杂化它,它使用不同的数据帧。这个图层将点之下(如果它在上面就可以正常工作):

one_timers %>% 
  ggplot(aes(x = date, y = event)) +
  geom_segment(data = sequence,
               aes(x = from,
                   xend = to,
                   y = event,
                   yend = event,
                   colour = quality),
               size = 3) +
  geom_point()

plot with broken chronology again

我尝试从第二个数据框强制event来考虑相同级别和排序因素,但不是这样(图片根本不会改变):

factors <- list(one_timers$event, sequence$event %>% as.factor())
sequence$event <- fct_unify(fs = factors)[[2]]  
sequence$event

one_timers %>% 
  ggplot(aes(x = date, y = event)) +
  geom_segment(data = sequence,
               aes(x = from,
                   xend = to,
                   y = event,
                   yend = event,
                   colour = quality),
               size = 3) +
  geom_point()
# still doesn't work

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

有趣的是,添加分段图层会使轴混乱 我设法通过引入一个数值变量来解决这个问题:

one_timers <- one_timers %>% mutate(eventNum = as.numeric(event))
sequence <- sequence %>% mutate(eventNum = which(levels(one_timers$event) %in% event))

one_timers %>% 
  ggplot(aes(x = date, y = eventNum)) +
  geom_segment(data = sequence,
               aes(x = from,
                   xend = to,
                   y = eventNum,
                   yend = eventNum,
                   colour = quality),
               size = 3) +
  geom_point() + 
  scale_y_continuous("event", 
                   breaks = one_timers$eventNum, 
                   labels = as.character(one_timers$event))

enter image description here