Open In App

Treemap with ggplot2 and treemapify in R

Last Updated : 16 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

TreeMaps are used to visualize the hierarchical data. A tree map is divided into rectangular boxes where the first rectangular box is the root of all the boxes, present in the graph. The hierarchy from most to least valued data , is plotted in the TreeMap. In this article, we are going to learn Treemap with ggplot2 and treemapify in R programming language.

Methods to plot Tree Map In R

1. Installing Necessary Requirements

First we need to install and load ggplot2 and treemapify.

R
install.packages("ggplot2")
install.packages("treemapify")

library(ggplot2)
library(treemapify)

2. Creating Sample Data

We create a sample data frame of fruit sales which can be used for plotting.

R
df<- data.frame(
                Fruits=c("Banana","Apple","Melon",
                         "Plums","Pineapple","Orange",
                         "Apricot","Grapes"),
                         
                 sales=c(25000,22000,15000,5000,
                         18000,20000,3000,9000)
                )

3. Plotting the TreeMap

We now plot the Simple TreeMap with the help of ggplot() and geom_treemap() functions.

R
ggplot2::ggplot(df,aes(area=sales,fill=sales))+
  treemapify::geom_treemap()

Output:

Fruit_Sales_Treemap
Fruit Sales Treemap

Adding labels to the tiles

To make the plot more interactive let's Customize the above TreeMap by adding text labels to each and every rectangular box and also by adding the title to the plot.

R
ggplot2::ggplot(df,aes(area=sales,fill=Fruits,label=Fruits))+
  treemapify::geom_treemap(layout="squarified")+
  geom_treemap_text(place = "centre",size = 12)+
  labs(title="Customized Tree Plot using ggplot and treemapify in R")

Output:

Customized_Tree_Plot
Customized_Tree_Plot

Subgroup tree plot

The subgrouped tree plot in our example the fruits are divided based on their availability in different seasons can be plotted by initialization the subgroup attribute in aesthetics(aes) of the plot in ggplot() function as follows:

R
df<- data.frame(Fruits=c("Banana","Apple","Melon",
                         "Plums","Pineapple","Orange",
                         "Apricot","Grapes"),
                
                Season=c("All Time","Winter","Summer",
                        "All Time","Winter","Summer",
                        "All Time","All Time"),
                
                sales=c(25000,22000,15000,5000,
                        18000,20000,3000,9000)
                )


ggplot2::ggplot(df,aes(area=sales,fill=Season,
                       label=Fruits,subgroup=Season))+
  treemapify::geom_treemap(layout="squarified")+
  geom_treemap_text(place = "centre",size = 12)+
  labs(title="Sub Grouped Tree Plot using ggplot and treemapify in R")

Output:

Sub_Grouped_Tree_Plot
Sub_Grouped_Tree_Plot

Next Article

Similar Reads