concept tree map in category R

appears as: tree maps, A tree map, tree map
R in Action, Third Edition MEAP V05

This is an excerpt from Manning's book R in Action, Third Edition MEAP V05.

The following sections explore the use of bar charts, pie charts, tree maps, histograms, kernel density plots, box plots, violin plots, and dot plots. Some of these may be familiar to you, whereas others (such as tree charts or violin plots) may be new to you. The goal, as always, is to understand your data better and to communicate this understanding to others. Let’s start with bar charts.

An alternative to a pie chart is a tree map. A tree map displays the distribution of a categorical variable using rectangles that are proportional to variable levels.  Unlike pie charts, tree maps can handle categorical variables with many levels. We'll create tree maps using the treemapify package. Be sure to install it before proceeding (install.packages("treemapify")). 

We'll start by creating a tree map displaying the distribution of car manufacturers in the mpg data frame. The code is given in listing 6.6. The resulting graph is giving fin figure 6-12.

Listing 6.6 Simple Tree Map
library(ggplot2)
library(dplyr)
library(treemapify)
 
plotdata <- mpg %>% count(manufacturer) #1
 
ggplot(plotdata,                        #2
       aes(fill = manufacturer,
           area = n,
           label = manufacturer)) +
geom_treemap() +
geom_tree_text() +
theme(legend.position = FALSE)

First we calculate the frequency counts for each level the manufacturer variable #1. This information is passed to ggplot2 to create the graph #2.  In the aes()  function, fill refers to the categorical variable, area is the count for level, and label is the option variable used to label the cells. The geom_treemap() function creates the tree map and the geom_tree_text() function adds the labels to each cell. The theme() function is used to suppress the legend, which is redundant here, since each cell is labeled.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest