Treemap Charts in R

How to make treemap charts in R with Plotly.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Treemap charts visualize hierarchical data using nested rectangles. Just like with a sunburst chart, the hierarchy of a treemap is defined by using the labels, and parents attributes.

Treemaps created with Plotly's R graphing library are interactive by default! Click on individual sectors of the treemap chart to zoom in/out of that sector and to display a hierarchical pathbar at the top of the chart. You can use this pathbar to zoom in/out of chart sectors instead of clicking on the sectors directly.

Basic Treemap

library(plotly)

fig <- plot_ly(
  type="treemap",
  labels=c("Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"),
  parents=c("", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve")
)
fig

Customize Treemap Attributes

You can customize several attributes of the treemaps you create with Plotly for R, including:

  1. values: a list of the values assigned to each chart sector.
  2. textinfo: determines the textual information that will appear in each chart sector. Valid values are text, value, current path, percent root, percent entry, percent parent, or any combination of the preceding.
  3. pathbar: determines whether the pathbar is visible when users zoom into chart sectors.
  4. branchvalues: the method that has been used to calculate the values of chart sectors that have desendants. Valid values for this attribute are total and remainder; the default value is remainder.
    • When set to remainder, items in the values attribute which correspond to the root of the chart and the branches sectors are taken to be the extra part not part of the sum of the values at their leaves.
    • When set to total, a brach's value is taken to be equal to the sum of the values of each chart sector that is a descendant of that branch. This behavior is demonstrated in the second trace in the example figure below- the value of the Eva branch is 65, which is the sum of the values of each chart sector that is a descendant of that branch (14 + 12 + 10 + 2 + 6 + 6 + 1 + 4).
library(plotly)

labels = c("Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura")
parents = c("", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve")

fig <- plot_ly(
  type='treemap',
  labels=labels,
  parents=parents,
  values= c(10, 14, 12, 10, 2, 6, 6, 1, 4),
  textinfo="label+value+percent parent+percent entry+percent root",
  domain=list(column=0))

fig <- fig %>% add_trace(
  type='treemap',
  branchvalues="total",
  labels=labels,
  parents=parents,
  values=c(65, 14, 12, 10, 2, 6, 6, 1, 4),
  textinfo="label+value+percent parent+percent entry",
  outsidetextfont=list(size=20, color= "darkblue"),
  marker=list(line= list(width=2)),
  pathbar=list(visible= FALSE),
  domain=list(column=1))

fig <- fig %>% layout(
  grid=list(columns=2, rows=1),
  margin=list(l=0, r=0, b=0, t=0))

fig

Set Color of Treemap Sectors

There are three different attributes you can use to change the color of the sectors of treemaps you have created with Plotly for R:

  1. marker.colors
  2. marker.colorscale
  3. colorway,

The following examples show how to use each attribute. To use marker.colors, pass a list of valid CSS colors or hexadecimal color codes.

library(plotly)

labels = c("A1", "A2", "A3", "A4", "A5", "B1", "B2")
parents = c("", "A1", "A2", "A3", "A4", "", "B1")

fig <- plot_ly(
  type="treemap",
  labels=labels,
  parents=parents,
  marker=list(colors=c("#000", "royalblue", "lightgray", "purple", "#FFF", "lightgray", "lightblue")))
fig

The following example uses the marker.colorsclae attribute. Rather than using a list of colors, simply supply a colorscale.

The built-in colorscales are: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blues, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis, and Cividis

library(plotly)

labels = c("A1", "A2", "A3", "A4", "A5", "B1", "B2")
parents = c("", "A1", "A2", "A3", "A4", "", "B1")
values = c("11", "12", "13", "14", "15", "20", "30")

fig <- plot_ly(
  type="treemap",
  labels=labels,
  parents=parents,
  values=values,
  marker=list(colorscale='Reds'))

fig

The following example uses the treemapcolorway attribute, which should be set in the chart's layout.

library(plotly)

labels = c("A1", "A2", "A3", "A4", "A5", "B1", "B2")
parents = c("", "A1", "A2", "A3", "A4", "", "B1")

fig <- plot_ly(
  type="treemap",
  labels=labels,
  parents=parents)

fig <- fig %>% layout(treemapcolorway=c("pink","lightgray"))
fig

Nested Layers in Treemap

The following example demonstrates how treemap charts can be used to reveal insights into the structure of hierarchical data that includes information about layers and grouping. The maxdepth attribute can be used to control how many levels of data are rendered; the default value of -1 renders all the levels in the hierarchy.

library(plotly)

df1 = read.csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/sunburst-coffee-flavors-complete.csv')
df2 = read.csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/coffee-flavors.csv')

fig <- plot_ly(
  type='treemap',
  ids=df1$ids,
  labels=df1$labels,
  parents=df1$parents,
  domain=list(column=0))

fig <- fig %>% add_trace(
  type='treemap',
  ids=df2$ids,
  labels=df2$labels,
  parents=df2$parents,
  maxdepth=1,
  domain=list(column=1))
fig <- fig %>% layout(grid=list(columns=2, rows=1))
fig

Controlling Text Font Size with uniformtext

By default, the font size of text labels in your treemap chart will vary to fit into the available space within a sector. However, if you want all the text labels in your treemap chart to have the same font size, you can use the uniformtext layout parameter. The minsize attribute sets the font size, and the mode attribute sets what happens to labels which cannot fit within a sector with the specified fontsize: either hide them or show them with overflow.

library(plotly)
df = read.csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/sunburst-coffee-flavors-complete.csv')
fig <- plot_ly(
  type='treemap',
  ids=df$ids,
  labels=df$labels,
  parents=df$parents)

fig <- fig %>% layout(uniformtext=list(minsize=10, mode='hide'))
fig

Reference

See https://plotly.com/r/reference/#treemap for more information and chart attribute options!

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)