【问题标题】:Calculating var by year to plot geom_line()按年份计算 var 以绘制 geom_line()
【发布时间】:2023-02-11 09:09:10
【问题描述】:

我有一个数据集,其中包含每年的一系列观察结果。我只想按年计算“失败”和“参加”的百分比,然后在同一个图上用 geom_line() 绘制年度趋势。我开始使用下面的代码,但它不太正确——我认为它需要按年份折叠?

代码:

df %>% 
  group_by(year) %>% 
  mutate(perc_fail = fail/sum(fail),
         perc_attend = attend/sum(attend)) %>% 
  ggplot(., aes(x = year)) +
  geom_line()

数据:

df < -structure(list(year = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 
4L, 4L, 4L, 4L, 4L), .Label = c("2000", "2001", "2002", "2003"
), class = "factor"), 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", 
  

【问题讨论】:

    标签: r ggplot2 tidyverse


    【解决方案1】:

    您可以使用 summarise() 而不是 mutate() 来获取每年的单个值,然后绘制。请注意,当您从不同的变量绘制不同的系列时,您可以将您想要的标签放在美学的图例中(就像我在 geom_line() 调用中对颜色所做的那样。

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

    您还可以将数据转换为长格式并使用 state_summary() 为您生成摘要统计信息。下面的代码将生成相同的图表。

    df %>% 
      mutate(year = as.numeric(as.character(year))) %>% 
      pivot_longer(c("fail", "attend"), names_to="status", values_to = "vals") %>% 
      ggplot(aes(x=year, y = vals, colour=status)) + 
      stat_summary(fun = mean, geom="line") +  
      labs(y="Percent", 
           x="Year", 
           colour ="") + 
      scale_y_continuous(labels=~scales::percent(.x))
    

    【讨论】:

      猜你喜欢
      • 2018-07-11
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多