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

如何绘制含类别簇的堆叠环形柱状图展示疼痛诊断组共病数据?

实现堆叠环形柱状图展示共病诊断分布

需求说明

需绘制堆叠环形柱状图,将11个病症类别划分为独立簇,从内到外依次展示FM、CR、CM、HC四个诊断组的共病频率分布,用ggplot2实现。

解决方案步骤

1. 加载依赖包

library(ggplot2)
library(dplyr)
library(tidyr)

2. 数据预处理

补全数据中缺失的组记录(确保每个病症在所有组都有对应频率,缺失则填充0),并为每个组设置环形层级:

# 假设你的数据框名为df,先补全缺失记录
df_complete <- df %>%
  complete(Category, Condition, Group, fill = list(Frequency = 0))

# 定义组的内外顺序:FM(内侧)→ CR → CM → HC(外侧)
group_order <- c("FM", "CR", "CM", "HC")
df_complete <- df_complete %>%
  mutate(
    Group = factor(Group, levels = group_order),
    ring_level = as.integer(Group)  # 用整数标记环形层级
  )

# 计算每个类别-组内的累积频率,用于堆叠显示
df_complete <- df_complete %>%
  group_by(Category, Group) %>%
  arrange(Condition) %>%
  mutate(
    cum_freq = cumsum(Frequency),
    prev_freq = lag(cum_freq, default = 0)
  ) %>%
  ungroup()

3. 绘制堆叠环形图

通过geom_col结合极坐标实现环形效果,每个组对应一层环,每个类别对应一个独立扇区:

ggplot(df_complete, aes(x = Category, fill = Condition)) +
  # 绘制堆叠柱,y=Frequency控制堆叠高度,width控制环的厚度
  geom_col(aes(y = Frequency, width = 0.8), 
           position = "stack", color = "white", size = 0.2) +
  # 转换为极坐标,将x轴转为环形角度
  coord_polar(theta = "x") +
  # 设置y轴刻度对应不同诊断组
  scale_y_continuous(
    breaks = seq_along(group_order),
    labels = group_order,
    expand = c(0, 0)
  ) +
  # 优化主题样式
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 90, hjust = 1, size = 10),
    axis.text.y = element_text(size = 10),
    panel.grid = element_blank(),
    legend.position = "right",
    legend.title = element_text(size = 11),
    plot.title = element_text(hjust = 0.5, size = 14)
  ) +
  labs(
    title = "疼痛病症患者共病诊断分布",
    x = "病症类别",
    y = "诊断组",
    fill = "具体病症"
  )

4. 优化调整(可选)

  • 扇区间隙:若需要让11个类别形成独立簇(扇区之间留空白),可以调整x轴位置:
df_complete <- df_complete %>%
  mutate(
    Category = factor(Category),
    x_pos = as.integer(Category) + 0.15  # 为每个类别添加偏移,制造间隙
  )

# 绘图时替换x=x_pos,并调整width
ggplot(df_complete, aes(x = x_pos, fill = Condition)) +
  geom_col(aes(y = Frequency, width = 0.7), 
           position = "stack", color = "white", size = 0.2) +
  coord_polar(theta = "x") +
  scale_x_continuous(
    breaks = seq_along(unique(df_complete$Category)),
    labels = unique(df_complete$Category)
  ) +
  # 其余设置同上述绘图代码
  • 归一化处理:如果不同组频率差异过大导致内侧环拥挤,可将频率转为组内占比:
df_complete <- df_complete %>%
  group_by(Group) %>%
  mutate(prop = Frequency / sum(Frequency)) %>%
  ungroup()

# 绘图时将y替换为prop即可
  • 图例优化:由于有94种病症,可调整图例布局:
guides(fill = guide_legend(ncol = 2, title.position = "top", title.hjust = 0.5))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:44:52