Search code examples
rtreemap

treemap [R]: how to fix the color assignment


I'm making series of treemaps, and want "A" in each plot always has the same color, and "B" in each plot always has the same color, etc.

The vSize of "A" may even be 0 in some plots - I padded rows of 0 in this case, but this didn't fix the issue. Can somebody help please... Thanks!

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()              
}

enter image description here enter image description here


Solution

  • You need to set drop.unused.levels = FALSE in the call to treemap. It is TRUE by default.

    A side effect though is that the legend on each plot will then show all levels of the town factor, even levels which do not occur on a particular plot. You may or may not like that...