如何在R中绘制60分钟时钟式环形图展示时段对应操作
R环形时钟图优化实现
需求概述
- 基于60分钟时间轴绘制环形图,用彩色条对应各时段操作
- 将所有带
Inactive前缀的操作合并为同一组,使用相同填充色 - 确保各操作与对应时间区间精准匹配
现有代码
attach(clock_data) hsize <- 4 clock_data <- clock_data %>% mutate(x = hsize) ggplot(clock_data, aes(x = hsize, y = Time, fill = Action)) + geom_col() + coord_polar(theta = "y") + xlim(c(0.2, hsize + 0.5)) + theme_bw()
数据结构
structure(list(Time_Between = c("0-15", "15-30", "30-33", "33-34", "34-35", "35-36", "36-40", "40-55", "55-56", "56-60"), Time = c(15L, 15L, 3L, 1L, 1L, 1L, 4L, 15L, 1L, 4L), Action = c("Inactive1", "Acoustic Sampling", "Inactive2", "SSH Tunnel", "Inactive3", "Switch Pi", "Data Copy", "Data Transmission", "Switch Mini", "Inactive4"), x = c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4)), row.names = c(NA, 10L), class = "data.frame")
优化解决方案
步骤1:合并Inactive操作组
先对数据预处理,把所有Inactive开头的操作统一命名,实现分组:
library(dplyr) library(ggplot2) # 合并所有Inactive类操作 clock_data <- clock_data %>% mutate(Action = ifelse(grepl("Inactive", Action), "Inactive", Action))
步骤2:调整环形图绘制逻辑
基于原框架优化,让图形更贴近时钟样式,同时确保时段匹配:
hsize <- 4 ggplot(clock_data, aes(x = hsize, y = Time, fill = Action)) + geom_col(color = "white") + # 白色边框区分不同时段 coord_polar(theta = "y", start = 0) + # 从顶部0/60分钟开始,符合时钟习惯 xlim(c(0, hsize + 0.5)) + # 添加时钟刻度标签 scale_y_continuous(breaks = c(0,15,30,45), labels = c("0/60","15","30","45")) + theme_bw() + theme( axis.text.x = element_text(size = 12), axis.title = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank() # 移除网格线,简化视觉效果 ) + labs(fill = "操作类型") # 图例标题
效果说明
- 所有
Inactive1/2/3/4统一显示为Inactive组,共用同一种填充色 - 每个条形长度严格匹配对应时段的分钟数,环形顺时针对应时间流逝
- 白色边框清晰划分不同操作的时间区间,刻度标签符合时钟阅读习惯
内容的提问来源于stack exchange,提问作者Jackson A Swan
相关产品推荐
相关产品推荐

