Different colors with gradient for subgroups on a treemap ggplot2 R

前端 未结 2 1236
不思量自难忘°
不思量自难忘° 2020-12-10 16:28

I have a treemap plot (shown below). The only change that I want to have is to change the color of subgroup (YEAR in the plot) to different colors, not all blue. Is this pos

2条回答
  •  Happy的楠姐
    2020-12-10 16:42

    It's not the most beautiful solution, but mapping count to alpha simulates a light-to-dark gradient for each color. Add aes(alpha = CNT) inside geom_treemap, and scale alpha however you want.

    library(ggplot2)
    library(treemapify)
    
    PL <- c(rep("PL1",4),rep("PL2",4),rep("PL3",4),rep("PL4",4))
    CNT <- sample(seq(1:50),16)
    YEAR <- rep(c("2015","2016","2017","2018"),4)
    
    df <- data.frame(PL,YEAR,CNT)
    
    ggplot(df, aes(area = CNT, fill = YEAR, label=PL, subgroup=YEAR)) +
    
    # change this line
        geom_treemap(aes(alpha = CNT)) +
        geom_treemap_subgroup_border(colour="white") +
        geom_treemap_text(fontface = "italic",
                                            colour = "white",
                                            place = "centre",
                                            grow = F,
                                            reflow=T) +
        geom_treemap_subgroup_text(place = "centre",
                                                             grow = T,
                                                             alpha = 0.5,
                                                             colour = "#FAFAFA",
                                                             min.size = 0) +
        scale_alpha_continuous(range = c(0.2, 1))
    

    Created on 2018-05-03 by the reprex package (v0.2.0).

    Edit to add: Based on this post on hacking faux-gradients by putting an alpha-scaled layer on top of a layer with a darker fill. Here I've used two geom_treemaps, one with fill = "black", and one with the alpha scaling. Still leaves something to be desired.

    ggplot(df, aes(area = CNT, fill = YEAR, label=PL, subgroup=YEAR)) +
        geom_treemap(fill = "black") +
        geom_treemap(aes(alpha = CNT)) +
        geom_treemap_subgroup_border(colour="white") +
        geom_treemap_text(fontface = "italic",
                                            colour = "white",
                                            place = "centre",
                                            grow = F,
                                            reflow=T) +
        geom_treemap_subgroup_text(place = "centre",
                                                             grow = T,
                                                             alpha = 0.5,
                                                             colour = "#FAFAFA",
                                                             min.size = 0) +
        scale_alpha_continuous(range = c(0.4, 1))
    

    Created on 2018-05-03 by the reprex package (v0.2.0).

提交回复
热议问题