【问题标题】:treemap [R]: how to fix the color assignmenttreemap [R]:如何修复颜色分配
【发布时间】:2026-01-07 11:25:08
【问题描述】:

我正在制作一系列树形图,并且希望每个图中的“A”始终具有相同的颜色,并且每个图中的“B”始终具有相同的颜色,等等。

在某些图中,“A”的 vSize 甚至可能为 0 - 在这种情况下,我填充了 0 行,但这并不能解决问题。有人可以帮忙吗...谢谢!

library(dplyr)
library(treemap)

#set directory
setwd('')

nRow = 200

dt1 = data.frame(month = sample(month.abb, nRow, replace=T),
                 town = sample(LETTERS, nRow, replace=T),
                 count = sample(1:100, nRow, replace=T))

# make some towns bigger so that it's easier to see
dt1[dt1$town=='A', 'count'] = dt1[dt1$town=='A', 'count'] + 500
dt1[dt1$town=='B', 'count'] = dt1[dt1$town=='B', 'count'] + 400
dt1[dt1$town=='C', 'count'] = dt1[dt1$town=='C', 'count'] + 300
dt1[dt1$town=='D', 'count'] = dt1[dt1$town=='D', 'count'] + 200
dt1[dt1$town=='E', 'count'] = dt1[dt1$town=='E', 'count'] + 100

empty = data.frame(name = LETTERS,
                   count = rep(0, length(LETTERS)))

for (i in 1:length(month.abb)){

        byTownEachMonth = dt1 %>%
                filter( month == month.abb[i] ) %>%
                group_by(town) %>%
                summarise( count = sum(count) )

        # pad rows/towns of 0 count
        byTownEachMonth = rbind(byTownEachMonth, 
                                empty[ ! empty$town %in% byTownEachMonth$town, ] )

        byTownEachMonth = byTownEachMonth[order(byTownEachMonth$town), ]

        byTownEachMonth$label = paste0(byTownEachMonth$town, ' ', 
                                       byTownEachMonth$count)

        png(width=800, height=600, file=paste0('tm_', month.abb[i], '.png'))

                treemap(byTownEachMonth, 
                        index = 'label',
                        vSize ='count',
                        vColor = 'town',
                        type = 'categorical',
                        inflate.labels = F)          
        dev.off()              
}

【问题讨论】:

    标签: r treemap


    【解决方案1】:

    您需要在调用树形图时设置drop.unused.levels = FALSE。默认为TRUE

    一个副作用是每个地块上的图例将显示城镇因素的所有级别,甚至是特定地块上没有出现的级别。你可能喜欢也可能不喜欢……

    【讨论】:

    • 非常感谢@WhiteViking。 - 关于混乱的传说,我选择不显示它,因为索引已经显示了所需的信息。