如何格式化日期绘制时间序列折线图?ggplot绘图异常排查
问题:geom_line绘制出类似条形的图表而非折线图
数据与预处理过程
原始tibble数据occurrences结构:
count_ date_ <int> <dttm> 1 NA 1923-01-01 00:00:00 2 NA 1923-01-01 00:00:00 3 NA 1923-01-01 00:00:00 4 NA 1923-01-01 00:00:00 5 1 1923-03-23 00:00:00 6 1 1923-03-23 00:00:00 7 1 1923-03-23 00:00:00 8 1 1923-03-23 00:00:00 9 1 1923-03-26 00:00:00 10 1 1923-03-26 00:00:00
执行的预处理代码:
occurrences <- occurrences %>% mutate( count_ = replace_na(count_, 1), date_ = as_date(date_) )
处理后的数据结构:
count_ date_ <int> <date> 1 1 1923-01-01 2 1 1923-01-01 3 1 1923-01-01 4 1 1923-01-01 5 1 1923-03-23 6 1 1923-03-23 7 1 1923-03-23 8 1 1923-03-23 9 1 1923-03-26 10 1 1923-03-26
绘制折线图的代码:
ggplot(occurrencesTibble, mapping = aes(date_, count_)) + geom_line()
实际得到类似条形的图表,而非预期的折线效果。
解决方案
问题根源是同一日期存在多条重复记录,geom_line会为每个重复点绘制垂直连线,视觉上呈现条形。需要先对数据按日期聚合,确保每个日期仅保留一个统计值:
- 按日期聚合数据(以求和为例,可根据需求替换为均值等其他统计量)
occurrences_agg <- occurrences %>% group_by(date_) %>% summarise(total_count = sum(count_))
- 使用聚合后的数据绘制折线图
ggplot(occurrences_agg, aes(x = date_, y = total_count)) + geom_line()
若需要同时展示原始数据点和折线,可结合geom_point:
ggplot(occurrences_agg, aes(x = date_, y = total_count)) + geom_point(size = 2) + geom_line()
额外注意:绘图代码中使用的occurrencesTibble需与预处理后的对象occurrences保持变量名一致,避免对象不匹配导致的问题。
内容的提问来源于stack exchange,提问作者rinepry
相关产品推荐
相关产品推荐

