wilkox / treemapify

🌳 Draw treemaps in ggplot2
http://wilkox.org/treemapify
213 stars 18 forks source link

Set Colours of Subgroups? #46

Closed edent closed 3 years ago

edent commented 3 years ago

I love TreeMapify - it has made my life so much easier! Is there a way to specify the colours of the subgroups?

For example

library(ggplot2)
library(treemapify)

name <- c("France", "Germany", "Chad", "Mali")
population <- c(100, 200, 300, 400)
parent <- c("Europe","Europe","Africa","Africa")
df <- data.frame(name, population, parent)
ggplot(df, aes(area = population, label = name, subgroup=parent, fill=parent )) +
geom_treemap() +
geom_treemap_text(colour = "white", place = "centre", grow = TRUE)

The fill=parent seems to set the colours randomly. I thought I could change it to fill=c("red", "green" ...) or use #f00 but neither of those worked.

Is there a way to specify the fill colours?

Thanks!

wilkox commented 3 years ago

Hi Terence, thanks for your kind words about treemapify!

In ggplot2, the way a variable is expressed as a plot aesthetic is called a 'scale'. ggplot2 will automatically select a scale for each aesthetic, but you can manually override it with one of the scale_*() family of functions. For example, you can manually specify the fill colours by adding scale_fill_manual() to the plot:

library(ggplot2)
library(treemapify)

name <- c("France", "Germany", "Chad", "Mali")
population <- c(100, 200, 300, 400)
parent <- c("Europe","Europe","Africa","Africa")
df <- data.frame(name, population, parent)
ggplot(df, aes(area = population, label = name, subgroup=parent, fill=parent )) +
  geom_treemap() +
  geom_treemap_text(colour = "white", place = "centre", grow = TRUE) +
  scale_fill_manual(values = c("purple", "orange"))

Created on 2021-06-20 by the reprex package (v1.0.0)

Hope this helps!

edent commented 3 years ago

Perfect, thanks 😊