【问题标题】:Hiding "20" of year "20XX" when displaying axis ticks ggplot在显示轴时隐藏年份 \"20XX\" 的 \"20\" ticks ggplot
【发布时间】:2023-02-11 16:37:27
【问题描述】:

好的,借用与我之前的问题 (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"))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我们可能会添加

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

    -输出

    【讨论】:

      【解决方案2】:

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

      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 ="") 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多