Search code examples
rggplot2treemap

charts Treemap with ggplots and treemapify


I have simple data frame that I want to visualize with a treemap. I've made using ggplot and treemapify. It seems ok, but I am wondering how can I show both name and lab variables inside the treemap without showing one as a label and one in the legend .

Here is dummay sample and my try:

 library(ggplot2)
 library(treemapify)

 data <-
   data.frame(
     name = c("Group A", "Group B", "Group C", "Group D"),
     value = c(8, 22, 66, 4),
     lab = c("8%", "22%", "66%", "4%")
   ) %>%
   mutate(lab = as.factor(lab))



 ggplot(data, aes(area = value, fill = lab,  label = name)) +
   geom_treemap() +
   geom_treemap_text(
     colour = "white",
     place = "centre",
     size = 15,
   ) +
   scale_fill_brewer(palette = "Greens")

The treemap graph : enter image description here

I am trying to have a graph like this example enter image description here


Solution

  • You can concatenate the lab and name and specify it as the label inside aes:

    ggplot(data, 
    aes(area = value, fill = lab,label = paste(name,lab,sep="\n"))) +
       geom_treemap() +
       geom_treemap_text(
         colour = "white",
         place = "centre",
         size = 15)+
       scale_fill_brewer(palette = "Greens")
    

    If you would like to specify the order of the palette, for example darkest green goes to 66%, specify the levels of the lab in data, for example:

    data$lab = factor(data$lab,levels=c("4%", "8%", "22%", "66%"))
    # and plot
    

    enter image description here