基于R ggplot2绘制18/6小时双情境能量预算饼图的实现咨询
R实现能量预算饼图方案
前置依赖
需要先安装加载tidyverse工具包,用于数据处理和可视化:
install.packages("tidyverse") library(tidyverse)
数据清洗与预处理
先导入你提供的原始数据,同时清理多余的格式标记:
# 构造结构化数据集 raw_data <- tibble( Context = rep(c("Absent", "Present"), each = 7), Behaviour = rep(c("Burst", "高能耗游泳", "中能耗游泳", "低能耗游泳", "移动", "上升", "下降"), 2), With = c(2.7, 1.95, 1.95, 8.48, 0.85, 1.20, 1.41, 0.77, 1.25, 0.75, 1.69, 0.26, 0.97, 0.32) ) # 计算统计指标 plot_data <- raw_data %>% group_by(Context) %>% # 计算每个情境的总能耗、单行为在对应情境的占比 mutate(context_total = sum(With), behaviour_pct = With / sum(With)) %>% ungroup() %>% # 补充时长标注 mutate(Context_label = ifelse(Context == "Absent", "Absent(18小时)", "Present(6小时)"))
绘图代码
你需要的区分情境、且各情境内按行为拆分占比的饼图可以通过极坐标柱状图实现,效果匹配参考图要求:
ggplot(plot_data, aes(x = Context_label, y = With, fill = Behaviour)) + # 调整柱宽为1,贴合饼图样式 geom_col(width = 1, color = "white") + # 切换极坐标,y值映射为扇区角度 coord_polar("y") + # 清除无关背景元素 theme_void() + # 调整图例标题 labs(fill = "行为类型") + # 可自定义配色方案 scale_fill_brewer(palette = "Set3") + # 给每个扇区添加数值标签 geom_text(aes(label = round(With, 2)), position = position_stack(vjust = 0.5))
可选调整说明
如果你需要两个大情境的扇区占比严格匹配18:6的时长比例(而非默认的总能耗占比),可以在绘图前对能耗值做权重校准:
plot_data <- plot_data %>% mutate(weighted_With = ifelse(Context == "Absent", With * (6/18), With))之后把绘图代码中的
y = With替换为y = weighted_With即可。
内容的提问来源于stack exchange,提问作者Sharklady
相关产品推荐
相关产品推荐

