如何按时间追踪两组事件数量并绘制分组趋势图?
解决方法
先修正数据代码
你写的最后一行代码缺了闭合括号,先补上:
require(tidyverse) (df <- tribble( ~id, ~group, ~event, 1, "A", "2010/01/23", 2, "B", "2010/02/13", 3, "A", "2011/03/21", 4, "B", "2010/01/20", 5, "B", "2012/11/03", 6, "A", "2012/08/12" )) # 修正括号问题 df$event <- as.POSIXct(df$event, format = "%Y/%m/%d")
方案1:累计事件数折线图
要是想展示每个组别随时间的事件累积趋势,先排序再计算累计值,然后绘图:
# 按组别和时间排序,计算每组的累计事件数 df_cum <- df %>% arrange(group, event) %>% group_by(group) %>% mutate(cum_count = row_number()) # 画折线图 ggplot(df_cum, aes(x = event, y = cum_count, color = group)) + geom_line(linewidth = 1) + geom_point(size = 3) + # 加上数据点更直观 labs( x = "时间", y = "累计事件数量", color = "组别", title = "各组累计事件数随时间变化" ) + theme_minimal()
方案2:按时间区间统计的图表
如果要对比不同时间段(比如年、月)里各组的事件数量,先按时间区间分组统计,再绘图:
柱状图(适合对比数量差异)
# 按年份分组统计事件数 df_year <- df %>% mutate(year = lubridate::year(event)) %>% # 提取年份,lubridate属于tidyverse group_by(year, group) %>% summarise(event_num = n(), .groups = "drop") ggplot(df_year, aes(x = factor(year), y = event_num, fill = group)) + geom_col(position = "dodge", width = 0.7) + # 分组并列显示 labs( x = "年份", y = "事件数量", fill = "组别", title = "各组年度事件数量统计" ) + theme_minimal()
折线图(适合展示趋势变化)
ggplot(df_year, aes(x = year, y = event_num, color = group)) + geom_line(linewidth = 1) + geom_point(size = 3) + labs( x = "年份", y = "事件数量", color = "组别", title = "各组年度事件数量趋势" ) + theme_minimal()
补充说明
- 累计折线图能清晰看到每个事件发生时间对应的累计数量,适合追踪增长过程;
- 时间区间统计的图表可以调整粒度,比如要按月统计,把
lubridate::year(event)换成lubridate::floor_date(event, "month")就行。
内容的提问来源于stack exchange,提问作者pietrodito
相关产品推荐
相关产品推荐

