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

Highcharts R:树形图(Treemap)分组异常问题求助

解决highcharter树形图中Costcenter分组重复的问题

问题场景

使用highcharter包创建树形图时,出现同一Costcenter(如N2)被拆分为多个分组的问题,相关代码与数据如下:

数据定义

library(highcharter)
df=
structure(list(Costcenter = c("N1", "N1", "N1", "N1", "N1", "N1", 
"N1", "N1", "N2", "N2", "N2", "N2", "N2", "N2", "N3", "N3", "N4", 
"N5", "N5", "N6"), Vendor = c("L2", "L2", "L2", "L2", "L2", "L2", 
"L2", "L2", "L1", "L2", "L2", "L2", "L3", "L3", "L2", "L2", "L2", 
"L2", "L2", "L2"), absDiff = c(103.0776, 37.9086, 269.7629, 6.0888, 
515.388, 27.2604, 27.2604, 6.3608, 4.5434, 88.5966, 982.2193, 
139.4249, 0.5452, 722.9811, 130.3381, 147.8434, 271.8786, 88.5966, 
327.4065, 366.564), value = c(103.0776, 37.9086, 269.7629, 6.0888, 
515.388, 27.2604, 27.2604, 6.3608, 4.5434, 88.5966, 982.2193, 
139.4249, 0.5452, 722.9811, 130.3381, 147.8434, 271.8786, 88.5966, 
327.4065, 366.564), Tool = c("M1", "M2", "M4", "M5", "M6", "M9", 
"M10", "M11", "M8", "M5", "M9", "M10", "M3", "M7", "M4", "M5", 
"M5", "M5", "M10", "M5")), .Names = c("Costcenter", "Vendor", 
"absDiff", "value", "Tool"), row.names = c(NA, -20L), class = "data.frame")

树形图调用代码

hctreemap2(df, c("Costcenter", "Vendor", "Tool"), size_var = "absDiff", color_var = "value")

问题现象

生成的图表中N2分组被拆分为两个独立节点,而非合并为单个分组。


解决方案

问题根源是hctreemap2会按数据的原始行顺序构建层级结构,若同一Costcenter的行不连续,会被识别为多个独立分组。只需先对数据按层级列排序,确保同一Costcenter的行连续即可。

方法1:基础R排序

# 按Costcenter、Vendor、Tool依次排序
df_sorted <- df[order(df$Costcenter, df$Vendor, df$Tool), ]
# 生成树形图
hctreemap2(df_sorted, c("Costcenter", "Vendor", "Tool"), size_var = "absDiff", color_var = "value")

方法2:dplyr简洁排序

library(dplyr)
# 按层级列排序
df_sorted <- df %>% arrange(Costcenter, Vendor, Tool)
# 生成树形图
hctreemap2(df_sorted, c("Costcenter", "Vendor", "Tool"), size_var = "absDiff", color_var = "value")

排序后,同一Costcenter的所有行被归为连续块,hctreemap2就能正确识别并合并为单个分组,不会再出现重复的N2节点。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:15:45