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

如何在R中生成类似示例的定性频率热图?含颜色分箱优化

在R中生成问卷数据热图的解决方案

一、热图生成方法

原生heatmap()函数灵活性较差,推荐用ggplot2或pheatmap实现你需要的样式,以下是具体代码示例:

1. 使用ggplot2(适合长格式数据,可视化定制性强)

先将宽格式问卷数据转为长格式,再用geom_tile()绘制热图:

# 加载工具包
library(tidyverse)

# 替换为你的实际数据(比如df <- read.csv("your_data.csv"))
df <- tibble(
  ID = c(1,2,3,5,7,8,10,11,13,14,15),
  Q1 = c(3,5,NA,3,5,5,1,2,3,3,3),
  Q2 = c(1,5,1,3,1,4,5,1,2,NA,3),
  Q3 = c(3,5,NA,5,3,3,1,2,3,5,1),
  Q4 = c(3,5,NA,5,5,4,1,1,2,NA,1)
)

# 宽转长格式
df_long <- df %>% 
  pivot_longer(cols = starts_with("Q"), names_to = "Question", values_to = "Response")

# 绘制热图
ggplot(df_long, aes(x = Question, y = factor(ID))) +
  geom_tile(aes(fill = Response), color = "white") + # 白色边框区分单元格
  scale_fill_gradientn(
    colors = c("#e7f0fa", "#c9e2f6", "#95cbee", "#0099dc", "#005f9e"), # 渐变配色
    na.value = "gray90", # 未回答(NA)设为浅灰色
    breaks = 1:5,
    labels = c("Never", "Once/week", "2-3/week", "4-6/week", "Daily") # 替换为你的实际选项标签
  ) +
  labs(x = "问题", y = "受访者ID", fill = "回答频率") +
  theme_minimal() +
  theme(
    axis.text.y = element_text(size = 8),
    panel.grid = element_blank() # 移除网格线
  )

2. 使用pheatmap(适合矩阵形式,快速生成热图)

直接用宽格式数据转矩阵绘制:

library(pheatmap)

# 转换为矩阵,行名设为受访者ID
df_matrix <- df %>% column_to_rownames("ID")

# 绘制热图
pheatmap(
  df_matrix,
  color = colorRampPalette(c("#e7f0fa", "#c9e2f6", "#95cbee", "#0099dc", "#005f9e"))(5),
  na_col = "gray90", # NA对应的颜色
  labels_row = rownames(df_matrix),
  labels_col = colnames(df_matrix),
  legend_labels = c("Never", "Once/week", "2-3/week", "4-6/week", "Daily"),
  border_color = "white",
  show_rownames = TRUE,
  show_colnames = TRUE,
  main = "问卷回答热图"
)

二、科学设置颜色分界的方法

1. 基于问卷语义分界(最优选择)

你的数据是有序分类变量(1-5对应明确的频率等级),直接用原始的1-5作为颜色分界最合理,这样颜色与回答的语义直接对应,可读性最强。

2. 基于数据分位数(适用于分布不均的数据)

如果不同等级的样本量差异极大,可通过分位数划分区间,保证每个区间的样本量均衡:

# 计算回答值的五分位数(排除NA)
quantiles <- quantile(df_long$Response, na.rm = TRUE, probs = seq(0, 1, 0.2))
# 在ggplot中使用分位数作为分界
ggplot(df_long, aes(x = Question, y = factor(ID))) +
  geom_tile(aes(fill = Response), color = "white") +
  scale_fill_gradientn(breaks = quantiles, colors = viridis::viridis(5))

3. 颜色盲友好配色

避免红绿色系,推荐使用viridis或RColorBrewer的专业配色:

# 使用viridis配色(色弱友好)
library(viridis)
ggplot(df_long, aes(x = Question, y = factor(ID))) +
  geom_tile(aes(fill = Response), color = "white") +
  scale_fill_viridis(option = "mako", na.value = "gray90", breaks = 1:5, labels = c("Never", "Once/week", "2-3/week", "4-6/week", "Daily"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:05:34