代码之家  ›  专栏  ›  技术社区  ›  a_todd12

显示轴刻度ggplot时隐藏“20XX”年的“20”

  •  1
  • a_todd12  · 技术社区  · 3 年前

    好吧,借用与我之前的问题相同的数据(仍然得出相同的数字)( Calculating var by year to plot geom_line() ),在我的真实数据中,我有2000-2017年,所以X轴变得非常拥挤。

    但没有办法在这个范围内均匀地切出一个(不能每隔一个或每三分之一切一个,然后均匀地断开)。

    所以我想,当沿着x轴显示“年”变量时,我想从“20XX”中去掉“20”(所以只有02、03、04等)。有人能想出一个巧妙的办法吗?我尝试创建一个新的因子变量,它只是“year-2000”,所以是“02”、“03”等,但它不会保留或显示前导的0。

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    df %>% 
      group_by(year) %>% 
      summarise(perc_fail = mean(fail),
             perc_attend = mean(attend)) %>% 
      ggplot(., aes(x = year, group=1)) +
      geom_line(aes(y= perc_fail, colour="Fail")) + 
      geom_line(aes(y=perc_attend, colour="Attend")) + 
      labs(y="Percent", 
           x="Year", 
           colour ="") + 
      scale_y_continuous(labels=~scales::percent(.x))
    

    数据:

    structure(list(year = c(2000, 2000, 2000, 2000, 2000, 2000, 2000, 
    2000, 2000, 2000, 2000, 2000, 2000, 2001, 2001, 2001, 2001, 2001, 
    2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2002, 2002, 
    2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 2002, 
    2002, 2002, 2002, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003, 
    2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003, 2003), fail = c(0, 
    0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 
    0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 
    0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0), attend = c(1, 
    1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 
    1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 
    1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1)), row.names = c(NA, 
    -60L), spec = structure(list(cols = list(year = structure(list(), class = c("collector_double", 
    "collector")), fail = structure(list(), class = c("collector_double", 
    "collector")), attend = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), delim = ","), class = "col_spec"), problems = <pointer: 0x0000025df802ece0>, class = c("spec_tbl_df", 
    "tbl_df", "tbl", "data.frame"))
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   akrun    3 年前

    我们可以添加

     ... + 
     scale_x_continuous(labels = ~ substr(.x, 3, 4))
    

    -输出

    enter image description here

        2
  •  2
  •   TarJae    3 年前

    另一种方法是添加标签列:

    df %>% 
      group_by(year) %>% 
      summarise(perc_fail = mean(fail),
                perc_attend = mean(attend)) %>% 
      mutate(label_year = sprintf("%02d", year %% 100)) %>% 
      ggplot(., aes(x = label_year, group=1)) +
      geom_line(aes(y= perc_fail, colour="Fail")) + 
      geom_line(aes(y=perc_attend, colour="Attend")) + 
      labs(y="Percent", 
           x="Year", 
           colour ="") 
    

    enter image description here

    推荐文章