RStudio中基于Date与Char类型变量绘制年/月统计直方图
解决方法
1. 加载依赖包
先确保安装并加载tidyverse(包含数据处理工具dplyr和绘图工具ggplot2):
# 未安装则执行此句 install.packages("tidyverse") library(tidyverse)
2. 数据预处理
从Date列提取时间维度,再分组统计总数(以下提供两种统计逻辑,按需选择):
按年份统计
# 统计每年总记录数 yearly_total <- df %>% mutate(year = lubridate::year(Date)) %>% group_by(year) %>% summarise(total = n()) # 按Condition分类统计每年数量 yearly_by_condition <- df %>% mutate(year = lubridate::year(Date)) %>% group_by(year, Condition) %>% summarise(total = n())
按月份统计
# 按「年月」统计(保留年份,如2023-01) monthly_yearly <- df %>% mutate(month_year = lubridate::floor_date(Date, "month")) %>% group_by(month_year) %>% summarise(total = n()) # 按「月份」跨年份汇总(所有1月数据合并) monthly_total <- df %>% mutate(month = lubridate::month(Date, label = TRUE)) %>% group_by(month) %>% summarise(total = n())
3. 绘制年份统计图形
基础年份总数量柱状图
ggplot(yearly_total, aes(x = factor(year), y = total)) + geom_bar(stat = "identity", fill = "#2E86AB") + labs(title = "按年份统计记录总数", x = "年份", y = "总数") + theme_minimal()
按Condition分类的年份堆叠柱状图
ggplot(yearly_by_condition, aes(x = factor(year), y = total, fill = Condition)) + geom_bar(stat = "identity") + labs(title = "按年份统计各Condition数量", x = "年份", y = "总数", fill = "Condition类型") + theme_minimal()
4. 绘制月份统计图形
年月时间序列折线图
ggplot(monthly_yearly, aes(x = month_year, y = total)) + geom_line(color = "#2E86AB", linewidth = 1) + geom_point(size = 2) + labs(title = "按年月统计记录总数", x = "年月", y = "总数") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
跨年份月份汇总柱状图
ggplot(monthly_total, aes(x = month, y = total)) + geom_bar(stat = "identity", fill = "#F24C4E") + labs(title = "按月份统计记录总数(跨年份汇总)", x = "月份", y = "总数") + theme_minimal()
内容的提问来源于stack exchange,提问作者Usman YousafZai
相关产品推荐
相关产品推荐

