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 possible at all?
Sample data frame
PL <- c(rep("PL1", 4), repl("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)
Plot
PL <- c(rep("PL1", 4), repl("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)
# plot
library(ggplot2)
library(treemapify)
treeMapPlot <- ggplot(df, aes(area = CNT,
fill = CNT,
label=PL,
subgroup=YEAR)) +
geom_treemap() +
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)
treeMapPlot
If I change the fill
in aes
I can get this, but I lose the gradient. I need to keep these colors, but show the tiles with gradient color, meaning small CNT lighter, larger CNT darker
treeMapPlot <- ggplot(df, aes(area = CNT,
fill = YEAR,
label = PL,
subgroup = YEAR))
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)
insidegeom_treemap
, and scale alpha however you want.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_treemap
s, one withfill = "black"
, and one with the alpha scaling. Still leaves something to be desired.Created on 2018-05-03 by the reprex package (v0.2.0).
One option is to calculate the colors separately for each cell and then just plot them directly. This doesn't give you a legend, but arguably a legend isn't that useful anyways. (You'd need 4 separate legends, and those could be made and added to the plot if needed.)
It's also possible to generate color scales dynamically if you don't know ahead of time how many cases there will be:
Finally, you can manually define the hues of the color scales: