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

请求协助:基于分类数据分组计算标记比例并绘制热图

分组计算标记变量"Yes"比例并绘制热图

1. 生成统计表格

我们可以用dplyr和tidyr包完成分组统计与格式整理:

首先加载所需工具包:

# 未安装的话先执行安装
install.packages(c("dplyr", "tidyr", "ggplot2"))

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

接着处理原始数据,计算每个分组下各标记的"Yes"比例:

# 原始数据集
df1 <- data.frame(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                  AgeGroup = c("Y","O","Y","Y","Y","O","Y","O","O","Y"),
                  Sex = c("m","m","f","f","m","f","m","m","f","f"),
                  marker1 = c('yes', 'yes', 'no', 'yes', 'no','no', 'yes', 'no', 'yes', 'no'),
                  marker2 = c('no', 'yes', 'no', 'yes', 'no','yes', 'yes', 'no', 'yes', 'no'),
                  marker3 = c('yes', 'no', 'no', 'yes', 'yes','no', 'yes', 'no','no', 'yes'))

# 生成分组统计表格
summary_table <- df1 %>%
  # 按年龄组和性别分组
  group_by(AgeGroup, Sex) %>%
  # 计算每个marker的yes比例
  summarise(
    marker1 = mean(marker1 == "yes"),
    marker2 = mean(marker2 == "yes"),
    marker3 = mean(marker3 == "yes"),
    .groups = "drop"
  ) %>%
  # 合并分组名称为Y_m、O_m等格式
  mutate(Group = paste0(AgeGroup, "_", Sex)) %>%
  # 调整列顺序,把分组列放前面
  select(Group, marker1, marker2, marker3) %>%
  # 保留两位小数让结果更清晰
  mutate(across(marker1:marker3, ~round(.x, 2)))

# 查看最终统计结果
summary_table

运行后得到的统计表格如下:

Group marker1 marker2 marker3
  <chr>   <dbl>   <dbl>   <dbl>
1 O_f      0.5     1       0   
2 O_m      0.5     0.5     0   
3 Y_f      0.33    0.33    0.67
4 Y_m      0.67    0.33    1   

2. 绘制热图

用ggplot2绘制热图,直观展示各分组的标记比例:

# 先把宽格式数据转为长格式,适配绘图需求
plot_data <- summary_table %>%
  pivot_longer(cols = marker1:marker3, names_to = "Marker", values_to = "Yes_Proportion")

# 绘制热图
ggplot(plot_data, aes(x = Marker, y = Group, fill = Yes_Proportion)) +
  # 添加热图瓷砖,白色边框区分区域
  geom_tile(color = "white") +
  # 在瓷砖上标注具体比例数值
  geom_text(aes(label = Yes_Proportion), color = "black", size = 5) +
  # 设置颜色渐变,浅色调对应低比例,深色调对应高比例
  scale_fill_gradient(low = "#f0f9e8", high = "#2b8cbe") +
  # 使用简洁的主题风格
  theme_minimal() +
  # 设置图表标签
  labs(
    x = "标记项",
    y = "分组",
    fill = "Yes比例",
    title = "各分组标记变量的Yes比例热图"
  ) +
  # 调整主题细节,让图表更美观
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    axis.title = element_text(size = 12),
    axis.text = element_text(size = 10)
  )

运行代码后会生成热图:x轴为三个标记项,y轴为四个分组,瓷砖颜色深浅对应"Yes"比例高低,同时标注具体数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:45:16