R语言使用ggplot按Road分图绘制period分组的clusterNum统计柱状图
实现思路
- 第一步:先对原始数据做聚合统计,按
Road、period、clusterNum三个维度分组,计算每个分组的观测数量 - 第二步:分组柱状图绘制逻辑:x轴映射为
period,y轴映射为统计得到的数量,填充色映射为clusterNum,柱状图位置设置为并排排列 - 第三步:按
Road拆分图的两种实现方式:- 方式1:使用
facet_wrap按Road分面,在同一张画布生成多个子图,适合做整体对比 - 方式2:循环过滤不同
Road的子集分别绘图,可单独导出每张图到本地
- 方式1:使用
完整实现代码
1. 加载依赖包
library(dplyr) library(ggplot2)
2. 构造示例数据
data <- structure(list(clusterNum = c(2, 2, 2, 2, 2, 3, 2, 3, 3, 3),Road = c("Hualampong", "Hualampong", "Hualampong", "Hualampong","Hualampong", "Hualampong", "Hualampong", "Tonglor", "Tonglor","Tonglor"), period = c("06.00-06.15", "06.00-06.15", "06.16-06.30","06.16-06.30", "06.16-06.30", "06.16-06.30", "06.16-06.30","17.46-18.00", "17.46-18.00", "17.46-18.00")), row.names = c(NA,-10L), class = c("tbl_df", "tbl", "data.frame"))
3. 数据聚合统计
count_df <- data %>% group_by(Road, period, clusterNum) %>% summarise(cnt = n(), .groups = "drop")
4. 绘图实现
方式1:分面生成同画布多张子图
ggplot(count_df, aes(x = period, y = cnt, fill = as.factor(clusterNum))) + geom_col(position = position_dodge(width = 0.9), width = 0.8) + facet_wrap(~Road, scales = "free") + labs(x = "时间段", y = "统计数量", fill = "clusterNum") + theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
方式2:单独生成每张Road的独立图片
# 提取所有道路名称 road_unique <- unique(count_df$Road) # 循环生成并导出图片 for (road_name in road_unique) { sub_df <- filter(count_df, Road == road_name) p <- ggplot(sub_df, aes(x = period, y = cnt, fill = as.factor(clusterNum))) + geom_col(position = position_dodge(width = 0.9), width = 0.8) + labs(title = road_name, x = "时间段", y = "统计数量", fill = "clusterNum") + theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 导出到本地,文件名为对应道路名称 ggsave(paste0(road_name, "_分组柱状图.png"), p, width = 6, height = 4, dpi = 300) }
内容的提问来源于stack exchange,提问作者Yasumin
相关产品推荐
相关产品推荐

