You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ggplot2在R中绘制更美观的活动时长饼图?

从基础R pie函数转ggplot2绘制美观饼图的修改要点

要从基础R的pie()切换到ggplot2实现带标签、图例的美观饼图,核心需要调整以下5个方面:

  • 调整数据格式:ggplot2要求数据为长格式,需把原数据中veryActiveMinutes、FairlyActiveMinutes、lightlyActiveMinutes、SedentaryMinutes这4个宽格式变量,转换为「活动类型」和「分钟数」两列的结构,可通过tidyr::pivot_longer()实现。
  • 替换绘图逻辑:放弃pie()函数,改用ggplot2的图层组合:ggplot() + geom_bar(stat="identity")配合coord_polar("y"),将柱状图转换为饼图形态。
  • 添加直观标签:用geom_text()或geom_label()给每个饼块添加数值/占比标签,通过position_stack(vjust=0.5)让标签居中显示在饼块内部。
  • 优化图例与标注:给活动类型设置易懂的别名(比如把变量名转为「高强度活动」「中度活动」等),添加清晰的图表标题,隐藏饼图不需要的坐标轴元素(如x轴刻度、y轴文字)。
  • 美化视觉样式:使用scale_fill_*()设置和谐配色(比如scale_fill_brewer()),去除背景网格线,搭配简洁主题(如theme_minimal())。

完整代码示例

# 加载所需工具包
library(tidyverse)

# 1. 将宽格式数据转为长格式
df_activity_long <- df_activity %>%
  # 仅保留目标变量
  select(veryActiveMinutes, FairlyActiveMinutes, lightlyActiveMinutes, SedentaryMinutes) %>%
  # 转换为长格式
  pivot_longer(cols = everything(),
               names_to = "activity_type",
               values_to = "minutes") %>%
  # 给活动类型设置友好名称
  mutate(activity_type = case_when(
    activity_type == "veryActiveMinutes" ~ "高强度活动",
    activity_type == "FairlyActiveMinutes" ~ "中度活动",
    activity_type == "lightlyActiveMinutes" ~ "轻度活动",
    activity_type == "SedentaryMinutes" ~ "久坐"
  ))

# 2. 绘制ggplot2饼图
ggplot(df_activity_long, aes(x = "", y = minutes, fill = activity_type)) +
  geom_bar(stat = "identity", width = 1) +
  # 转为饼图
  coord_polar("y", start = 0) +
  # 添加内部标签(显示分钟数+占比)
  geom_text(aes(label = paste0(minutes, "min\n(", round(minutes/sum(minutes)*100, 1), "%)")),
            position = position_stack(vjust = 0.5)) +
  # 设置配色方案
  scale_fill_brewer(palette = "Set2") +
  # 添加标题和图例名称
  labs(title = "每日活动时长分布",
       fill = "活动类型") +
  # 美化主题,隐藏冗余元素
  theme_minimal() +
  theme(axis.title = element_blank(),
        axis.text = element_blank(),
        panel.grid = element_blank(),
        plot.title = element_text(hjust = 0.5, size = 14, face = "bold"))

内容的提问来源于stack exchange,提问作者Mimikul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:06:18