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

在R语言中实现嵌套层级热力图的技术问询

嵌套层级热力图实现方案

核心思路

用ggplot2的geom_tile()结合数据分层处理,通过调整tile的宽度/高度、位置和边框样式区分层级,手动控制元素位置实现嵌套结构,无需依赖特定的层级热力图包。

示例数据集构建

以大洲-国家-城市的人口层级为例,用tidyverse构建包含各层级汇总的数据:

library(tidyverse)

set.seed(123)
# 基础城市级数据
hierarchy_data <- tibble(
  continent = rep(c("亚洲", "欧洲"), each = 6),
  country = rep(c("中国", "日本", "韩国", "德国", "法国", "英国"), each = 2),
  city = c("北京", "上海", "东京", "大阪", "首尔", "釜山", "柏林", "慕尼黑", "巴黎", "里昂", "伦敦", "曼彻斯特"),
  population = sample(100:1000, 12)
) %>%
  # 追加国家、大洲层级的汇总数据
  bind_rows(
    group_by(., continent, country) %>%
      summarise(city = "国家汇总", population = sum(population), .groups = "drop"),
    group_by(., continent) %>%
      summarise(country = "大洲汇总", city = "", population = sum(population), .groups = "drop")
  ) %>%
  arrange(continent, country, city)

可视化实现代码

通过自定义位置偏移和tile尺寸,实现嵌套对齐效果:

# 为不同层级分配位置、宽度参数
hierarchy_data <- hierarchy_data %>%
  mutate(
    level = case_when(
      city == "" ~ "大洲",
      city == "国家汇总" ~ "国家",
      TRUE ~ "城市"
    ),
    # 自定义x轴位置,让层级嵌套对齐
    x_pos = case_when(
      level == "大洲" ~ as.integer(factor(continent)) * 10,
      level == "国家" ~ as.integer(factor(continent)) * 10 + as.integer(factor(country)) * 2,
      level == "城市" ~ as.integer(factor(continent)) * 10 + as.integer(factor(country)) * 2 + as.integer(factor(city)) * 0.8
    ),
    # 层级越高,tile宽度越宽
    tile_width = case_when(
      level == "大洲" ~ 8,
      level == "国家" ~ 1.6,
      level == "城市" ~ 0.7
    )
  )

# 绘制嵌套热力图
ggplot(hierarchy_data, aes(x = x_pos, y = level)) +
  geom_tile(aes(width = tile_width, fill = population, color = level), size = 1) +
  # 添加层级标签
  geom_text(aes(label = case_when(
    level == "大洲" ~ continent,
    level == "国家" ~ country,
    TRUE ~ city
  )), color = "white", fontface = "bold") +
  # 配色与主题调整
  scale_fill_viridis_c(option = "plasma") +
  scale_color_manual(values = c("大洲" = "#2d3436", "国家" = "#636e72", "城市" = "#b2bec3")) +
  theme_minimal() +
  theme(
    axis.text.y = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank(),
    legend.position = "right"
  )

关键技巧说明

  • 数据分层:手动生成各层级的汇总数据,确保每个层级都有对应的数据点用于绘制tile
  • 位置与尺寸控制:通过自定义x_pos和tile_width参数,让高层级tile覆盖对应子层级的横向范围,实现嵌套视觉效果
  • 样式区分:用边框颜色、tile尺寸区分层级,配合文本标签清晰展示结构
  • 灵活适配:如果是成本分类等其他层级结构,只需替换数据中的层级字段(如大洲→成本大类、国家→成本中类)即可复用代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:12:15