- Lab
- Data

Build a Treemap in Python to Visualize Tech Support Ticket Distribution
In this hands-on Code Lab, you’ll build interactive treemap visualizations in Python to analyze tech support ticket data. You’ll start with a simple treemap using Plotly Express and progressively customize it with colors, labels, and styling. Then, you’ll create an advanced treemap using Plotly Graph Objects for fine-grained control of hierarchy and formatting. By the end, you’ll have a polished, presentation-ready visualization that clearly communicates data distributions across priorities and issue categories.

Path Info
Table of Contents
-
Challenge
Step 1: Create a Basic Treemap
Step 1: Create a Basic Treemap
Treemaps are an excellent way to visualize hierarchical data, especially when you want to compare proportions across multiple categories. In this step, you'll build a treemap to explore tech support ticket volume by priority and issue category.
Plotly Express makes it simple to create interactive treemaps with just a few lines of code. You'll also learn how to apply color coding and customize hover labels to enhance the chart's readability.
What You’ll Learn in This Step
- Create a treemap using
px.treemap()
with a two-level hierarchy - Apply custom colors to distinguish ticket priority levels
- Enhance hover labels with additional information and formatting
Open the Notebook
From the workspace panel, open the notebook file:
1-step-one.ipynb
.info> Important: Save your notebook (Ctrl/Cmd + S) before clicking Validate. Validation checks the most recent saved checkpoint.
### Creating a Basic Treemap with Plotly ExpressHow to Complete Each Task
- Find the matching code cell labeled
Task 1.1
,Task 1.2
, etc. - Follow the
# TODO
comments in each cell to guide your work. - Run the cell using the Run button or press Shift+Enter.
- Save your progress using the Save icon or File > Save and Checkpoint.
- All code and output will appear inline in the notebook.
Treemaps help you visualize hierarchical data using nested rectangles. Each rectangle represents a category, and its size corresponds to a numerical value like count or volume.
How It Works
- Use Plotly Express’s
px.treemap()
function to generate treemaps by passing a list of columns passed to thepath
argument. - Set the
values
parameter to control the size of each tile based on a numeric column. - The top-level group appears first, followed by subcategories in a tree-like layout.
Syntax Example
fig = px.treemap( dataframe, path=['Level1', 'Level2'], values='ValueColumn' )
What This Treemap Shows
- The hierarchy groups tickets by Priority and then by Issue Category.
- The size of each tile represents the TicketCount.
- This helps you identify which issue types are most common, and which priorities dominate support volume.
Why This Is Useful
This visualization allows you to:
- Compare ticket volume across categories and priorities.
- Spot high-impact categories at a glance.
- Drill into subgroups in a clean and intuitive layout. ### Adding Color to Distinguish Priority Levels
Color is a powerful way to enhance your treemap and draw attention to key categories. By default, Plotly uses a standard color palette based on hierarchy.
In this task, you’ll override that behavior and assign custom colors based on the
Priority
column.How It Works
- You pass a column to the
color
parameter inpx.treemap()
to control tile color. - You can supply a
color_discrete_map
to define your own color palette.
Syntax Example
color='Priority', color_discrete_map={ 'High': '#EF553B', 'Medium': '#FFA15A', 'Low': '#00CC96' }
Visual Result
- Each tile is shaded according to its ticket priority.
- You can more easily compare categories within and across groups.
- Custom coloring improves readability by reinforcing visual groupings. ### Enhance Treemap Hover and Label Interactivity
In this task, you'll improve your treemap's interactivity and readability. You'll customize hover labels, control how much of the hierarchy is visible, and display values and percentages directly on each tile using
textinfo
.1. Add Custom Hover Data
The
hover_data
argument allows you to specify exactly which columns appear in the tooltip:hover_data={ 'IssueCategory': True, 'TicketCount': True }
This ensures consistent and useful context appears when hovering over any tile. It's especially important when space is limited or labels are hidden.
2. Limit Depth with
maxdepth
Use the
maxdepth
parameter to restrict how many levels of the hierarchy are shown by default. For example:maxdepth=2
This keeps your chart focused by hiding deeply nested levels unless the user drills down.
3. Show Labels, Values, and Percentages
You can display more information directly on each tile by updating the trace with
textinfo
:fig.update_traces(textinfo='label+value+percent parent')
This adds static labels showing:
- The group/category name
- The raw ticket count
- The percent of the parent category
Together, these enhancements improve both the interactivity and the legibility of your treemap.
- Create a treemap using
-
Challenge
Step 2: Apply Styling and Theme Customizations
Step 2: Apply Styling and Theme Customizations
Now that you’ve created a working treemap, you'll focus on visual polish. In this step, you’ll customize the color palette, add a title, and format labels to improve clarity and alignment with brand or presentation needs.
Plotly Express offers a flexible way to define discrete colors, apply titles, and control how information is displayed both in the chart and on hover.
What You’ll Learn in This Step
- Apply a custom color palette using
color_discrete_map
- Add a chart title and modify
textinfo
display - Show additional fields in hover labels
- Use
update_traces()
to control which labels appear in each tile
Open the Notebook
From the workspace panel, open the notebook file:
2-step-two.ipynb
.info> Important: Save your notebook (Ctrl/Cmd + S) before clicking Validate. Validation checks the most recent saved checkpoint.
### Customize Treemap Colors and TitleHow to Complete Each Task
- Find the matching code cell labeled
Task 2.1
,Task 2.2
, etc. - Follow the
# TODO
comments in each cell to guide your work. - Run the cell using the Run button or press Shift+Enter.
- Save your progress using the Save icon or File > Save and Checkpoint.
- All code and output will appear inline in the notebook.
Plotly Express makes it easy to apply color-based grouping and add titles directly to your treemaps.
How the
color
Argument Works- When you assign a column like
'Priority'
to thecolor
parameter, Plotly automatically groups and shades tiles based on its unique values. - For categorical columns, it uses a default color palette to assign distinct colors to each group.
- This makes your chart easier to scan visually and highlights patterns by group.
Using the
title
Parameter- You can provide a title directly in the
px.treemap()
function using thetitle
argument. - This appears as a heading above the chart and helps convey the chart’s purpose or context.
- Titles are especially helpful when exporting charts or embedding them into dashboards. ### Add Tile Labels and Percentages
Treemaps can show text directly on each tile, giving users more context without needing to hover. You customize this using the
textinfo
parameter in Plotly.How
textinfo
Works-
Use the
textinfo
argument to control what appears on each treemap tile. -
Provide a string of one or more options, separated by
+
. -
Common values include:
'label'
: shows the category name'value'
: shows the numeric value from thevalues
column'percent parent'
: shows the percentage of the parent node'percent entry'
: shows the percentage of the root node
Example
fig.update_traces(textinfo='label+value+percent parent')
This would display:
- The tile’s name (for example, “Network”)
- The ticket count (for example, “84”)
- The percentage that category contributes to its parent (for example, "32%")
Enhance Tile Readability with Labels and Hover Data
When building interactive charts, it's important to display key information both visually and through hover tooltips. Plotly Express lets you control what appears directly on each tile and what shows when a user hovers.
Show Data on Tiles Using
textinfo
The
textinfo
property controls what appears inside each rectangle. You can combine values like:'label'
: show the category name'value'
: display the numeric value (such as ticket count)'percent parent'
: show the category's percentage of its parent
Use a
+
-separated string to combine multiple options:fig.update_traces(textinfo='label+value+percent parent')
Customize Hover Behavior with
hover_data
Use the
hover_data
argument to specify which DataFrame fields appear in tooltips:hover_data={ 'IssueCategory': True, 'TicketCount': True }
This provides deeper insight without cluttering the chart.
- Apply a custom color palette using
-
Challenge
Step 3: Enhance Labels and Interactivity
Step 3: Enhance Treemap Interactivity
Now that your treemap is styled and color-coded, the next step is to increase its interactivity and insight delivery. Plotly allows you to customize hover labels, add drill-down depth, and show detailed context without cluttering the chart.
In this step, you'll improve the treemap's interactivity by adding more descriptive hover content and adjusting the hierarchical depth.
What You’ll Learn in This Step
- Customize the
hover_data
to include Subcategory and Description fields - Use
textinfo
to show labels, values, and parent percentages - Set
maxdepth
to control the visible levels in the hierarchy - Understand hover label behavior for grouped vs. row-level data
Open the Notebook
From the workspace panel, open the notebook file:
3-step-three.ipynb
.info> Important: Save your notebook (Ctrl/Cmd + S) before clicking Validate. Validation checks the most recent saved checkpoint.
### Add Interactivity with Hover Data and Depth ControlHow to Complete Each Task
- Find the matching code cell labeled
Task 3.1
- Follow the
# TODO
comments in the code cell - Run the cell using the Run button or Shift+Enter
- Save your work before validating
This task focuses on making the treemap more interactive while managing visual complexity by setting a maximum depth and customizing hover labels.
Key Features Introduced
hover_data
: Allows you to add additional column values that appear when hovering over each tile. This makes charts more informative without cluttering the layout.maxdepth
: Restricts how many levels of the hierarchy are shown at once. It helps reduce noise by hiding deeper levels unless clicked.
Syntax Overview
hover_data={ 'Subcategory': True, 'Description': True }, maxdepth=2
When to Use These
- Use
hover_data
to show helpful context like descriptions or detailed labels. - Use
maxdepth
to simplify visualizations with more than 2-3 levels of hierarchy. This keeps charts focused and readable.
Note: In this dataset,
Subcategory
andDescription
exist for every row, but are not part of the hierarchy. Including them as hover fields lets you expose that detail interactively. ### Show Values and Percentages on Treemap TilesIn addition to hover tooltips, Plotly treemaps allow you to render static text directly on each tile. This includes names, values, and relative percentages.
What Is
textinfo
?textinfo
is a trace-level property that controls what appears as text inside each treemap tile.You can include multiple pieces of information using a
+
-separated string.Each option adds a layer of insight:
'label'
: The group or category name'value'
: The raw numeric total (such as number of tickets)'percent parent'
: The percentage of the tile relative to its parent node
Syntax Example
fig.update_traces(textinfo='label+value+percent parent')
This results in each tile showing:
- The category name (for example, “Network”)
- Ticket volume (for example, “84”)
- Proportional size within its group (for example, “34%”)
This helps viewers make comparisons directly from the chart, even if they don’t hover. ### Enforce Consistent Font Sizes Using
uniformtext
When tiles in a treemap vary in size, their labels can scale differently, making small tiles hard to read. Plotly addresses this with the
uniformtext
setting applied at the layout level, not the trace level.What Is
uniformtext
?- It's a
layout
setting that ensures text across tiles appears with consistent sizing. - It prevents extremely small fonts and hides text if it can’t meet the threshold.
Syntax Example
fig.update_layout(uniformtext=dict(minsize=12, mode='hide'))
What This Does
minsize=12
: All visible tile labels must be at least 12 pixels tall.mode='hide'
: If a tile can’t fit the text at that size, the text is hidden instead of shrinking.
This keeps your chart readable and avoids cluttered or illegible text, especially when categories vary widely in size.
- Customize the
-
Challenge
Step 4: Build an Advanced Treemap with Graph Objects
Step 4: Build an Advanced Treemap with Graph Objects
In this step, you’ll move beyond the higher-level
plotly.express
API and build a treemap manually usingplotly.graph_objects
. This gives you full control over the tile layout, labels, interactivity, and aggregation logic.You'll construct your own hierarchy using
labels
,parents
, andvalues
, apply aggregation usingbranchvalues
, customize hover behavior, and apply a consistent color scheme for clarity.
What You’ll Learn in This Step
- Construct a treemap manually using
go.Treemap
- Define labels, parents, and values to control layout
- Aggregate tickets by category and priority using
branchvalues
- Customize tooltips and apply a custom color scheme by priority
Open the Notebook
From the workspace panel, open the notebook file:
4-step-four.ipynb
.info> Important: Save your notebook (Ctrl/Cmd + S) before clicking Validate. Validation checks the most recent saved checkpoint.
### Creating a Basic Treemap with Graph ObjectsHow to Complete Each Task
- Find the matching code cell labeled
Task 4.1
,Task 4.2
, etc. - Follow the
# TODO
comments in the code cell to guide your work. - Run the cell using the Run button or press Shift+Enter.
- Save your notebook before validating.
While
plotly.express
automates many chart features,plotly.graph_objects
gives you full control over the structure of your treemap.In this task, you’ll manually build the hierarchy by defining three parallel lists:
labels
: the text shown on each tileparents
: the parent of each node (or""
for root)values
: the size (such as ticket count) of each tile
What Is
branchvalues='total'
?This parameter tells Plotly how to interpret parent values:
'total'
: parent’s value equals the sum of its children (used here)'remainder'
: parent’s value equals total minus sum of children
By using these arrays and
go.Treemap
, you can build a fully customized chart layout.Example Output
You’ll create a root node titled
All Tickets
and display eachIssueCategory
underneath. Each tile will be sized by the number of support tickets in that category.Control Aggregation with
branchvalues
In Plotly Graph Object treemaps, the
branchvalues
parameter defines how a parent tile interprets its own value in relation to its children.You have two modes:
"total"
: the parent’s value represents the sum of its children"remainder"
: the parent’s value represents its own independent total, and child values are subtracted from it
When you use
"total"
, you must explicitly assign values at all levels of the hierarchy — including each parent node. Plotly will not automatically aggregate values upward. This gives you full control over how each node contributes to the visual structure.This mode is especially useful when:
- You’ve already pre-aggregated data by groups, such as totals by
Priority
- You need consistent totals across dashboards or exported metrics
- You want to visualize an exact hierarchy with no inferred roll-ups
Customizing Hover Tooltips in Treemaps
Treemaps created with Plotly Graph Objects offer detailed control over hover behavior using the
hovertemplate
parameter. This lets you replace the default tooltip content with fully customized text using data placeholders.The key benefit of
hovertemplate
is precision:- You choose exactly which fields to show
- You can format the text, reorder fields, and remove the extra tooltip footer
Useful placeholders include:
%{label}
: the name of the tile%{parent}
: the name of the parent node%{value}
: the value assigned to the tile%{percentParent}
: how much this tile contributes to its parent
By customizing hover templates, you ensure consistency across tiles and highlight exactly the information users need — especially useful when dealing with deep hierarchies or shared category names. #### Color-coding Treemap Tiles by Priority
When visualizing hierarchical data, color is a key tool for conveying group membership and making patterns more recognizable at a glance.
Plotly Graph Objects allow you to manually assign colors to each tile using the
marker.colors
property. This is especially useful when you want consistency across charts or to match organizational branding.In this case, each support ticket is tied to a priority; High, Medium, or Low. By defining a color for each priority level and applying it to both group and leaf tiles, we ensure:
- High-priority tickets are clearly marked (e.g., red)
- Medium and Low tickets use consistent visual cues
- The treemap remains readable, even when categories repeat
This approach reinforces group identity and improves visual scanability, especially on dense or multi-level charts.
- Construct a treemap manually using
-
Challenge
Step 5: Explore Advanced Coloring and Grouping
Step 5: Explore Advanced Coloring and Grouping
Now that you’ve mastered the basics of building and styling treemaps, you're ready to move into more advanced territory.
In this step, you’ll unlock deeper hierarchical visualization using Plotly Express’s
path
parameter. You’ll also explore both discrete and continuous color encoding — crucial for expressing both group membership and numerical variation. Finally, you’ll customize how the root node appears, ensuring visual polish even at the top of the hierarchy.
What You’ll Learn in This Step
- Add a third hierarchy level using the
path
parameter - Use color_continuous_scale to visualize magnitude
- Use color_discrete_map to encode group identity
- Set a custom root color for aesthetic consistency
Open the Notebook
From the workspace panel, open the notebook file:
5-step-five.ipynb
.info> Important: Save your notebook (Ctrl/Cmd + S) before clicking Validate. Validation checks the most recent saved checkpoint.
### Add a Third Hierarchy Level with the `path` ParameterHow to Complete Each Task
- Find the matching code cell labeled
Task 5.1
,Task 5.2
, etc. - Follow the
# TODO
comments in each cell to guide your work. - Run the cell using the Run button or press Shift+Enter.
- Save your progress using the Save icon or File > Save and Checkpoint.
- All code and output will appear inline in the notebook.
So far, your treemaps have displayed two levels:
Priority
andIssueCategory
. But Plotly Express allows for even deeper insight by supporting multiple nested levels through thepath
argument.By adding
Subcategory
as a third level, you can surface more granular trends inside each issue category. This is particularly useful for large datasets or complex systems where drilling down is necessary to understand the nature of support requests.How the
path
works:- It takes a list of column names, ordered from top-level (root) to lowest level (leaf).
- Plotly automatically constructs the tree based on those columns.
- Each level becomes a distinct branch in the treemap hierarchy.
This kind of multilevel view enables better storytelling, especially when paired with color and hover interactivity.
Apply a Continuous Color Gradient
Treemaps can use color not just for categorical grouping, but also for numeric intensity. When you assign a numeric column to the
color
argument in Plotly Express, it applies a continuous gradient using thecolor_continuous_scale
parameter.This is especially useful when you want to encode the magnitude of values visually, even within the same category.
In this case, you’ll use
TicketCount
as the color dimension:- Tiles with more tickets will appear darker or more saturated.
- Tiles with fewer tickets will appear lighter.
By layering this continuous scale on top of a multilevel path, you help users instantly identify which subcategories are driving the volume — even when categories have similar sizes.
Assign Fixed Colors to Categories Using
color_discrete_map
For categorical columns like "Priority", it’s important to maintain consistent color mappings across charts, especially in dashboards or multi-chart reports.
Plotly Express allows you to assign specific colors to each category using the
color_discrete_map
argument. This ensures that, for example,“High”
priority always appears red,“Medium”
orange, and“Low”
green.The benefit of using
color_discrete_map
is clarity and visual consistency. It helps your audience quickly recognize groupings and interpret the chart, even without a legend.This technique also works alongside hierarchical paths, so your treemap remains both color-consistent and structurally rich.
Set a Custom Root Color for the Treemap
By default, Plotly Express automatically assigns a color to every node in the hierarchy, including the root. But if your root node is just a logical container (such as “All Tickets”), it may be helpful to give it a neutral color so it doesn’t distract from meaningful data.
You can control the root node's appearance using the
root_color
parameter inside.update_traces()
:fig.update_traces(root_color="lightgrey")
This option is only available in Plotly Express (not Graph Objects), and it supports any valid CSS color name or hex code.
Why use a custom root color?
- Helps distinguish structural vs. data nodes
- Prevents the root from adopting a data-driven color (which could mislead)
- Matches UI styles for dashboards or embedded reports
Best practices:
- Use a neutral color like
"lightgrey"
or"#F0F0F0"
to keep focus on child tiles - Avoid using strong or categorical colors for the root
- Only apply
root_color
when the treemap has 2+ levels (so the root is actually visible)
- Add a third hierarchy level using the
What's a lab?
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Provided environment for hands-on practice
We will provide the credentials and environment necessary for you to practice right within your browser.
Guided walkthrough
Follow along with the author’s guided walkthrough and build something new in your provided environment!
Did you know?
On average, you retain 75% more of your learning if you get time for practice.