plotly

Plotly.Express.Treemap()

A treemap is one of the less common types of plots that you will encounter. However, it comes in handy when you need to display the hierarchical data. A treemap uses a sequence of nested rectangles to display the hierarchy defined by labels and attributes.

You can then click each rectangle sector to display the nested information inside it. Therefore, it is a great tool when you have a large hierarchy.

For this tutorial, we will explore how we can utilize the functionality of Plotly Express module to create the Treemaps.

If you are ready, let’s dive in.

Plotly.Express.Treemap()

As you probably guessed, to create a treemap in Plotly, we will use the treemap() function from the Express module.

The function syntax is as shown in the following:

plotly.express.treemap(data_frame=None, names=None, values=None, parents=None, ids=None, path=None, color=None, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, color_discrete_sequence=None, color_discrete_map=None, hover_name=None, hover_data=None, custom_data=None, labels=None, title=None, template=None, width=None, height=None, branchvalues=None, maxdepth=None)

The function has a relatively simple syntax. The most important parameters we need to know include:

  1. Data_frame – Specifies the data_frame holding the column names for the plot. You can pass this value as a DataFrame, a dictionary or an array_like object.
  2. names – This parameter defines the values used as the labels for the sectors.
  3. values – Refers to the values associated with the sectors.
  4. parents – Defines the values used as parents.
  5. ids – Specifies the values used to set the IDs of the sectors.
  6. path – Defines the values used for the hierarchy of the sectors.
  7. color – Defines the values used to assign a unique color to the marks.

Example 1:

Let us create a treemap using the Plotly express. We start by defining a list of names. We then define the parents of each parent in another list. We can then create a treemap of the family.

import plotly.express as px
names = ["Naomi", "Aaron", "Andrew", "Eddie", "Sarah", "Liz", "Lana"]
parents = ["", "Naomi", "Naomi", "Liz", "Lana", "", ""]
fig = px.treemap(names=names, parents=parents)
fig.show()

Once we run the code above, we see a treemap as shown in the following:

Example 2:

We can create the hierarchical treemap by specifying the different levels of hierarchy as a list of columns.

We can use the tips() data to illustrate this:

df = px.data.tips()

fig = px.treemap(df, path=['day', 'time', 'tip'], values='total_bill', color='day')

fig.show()

The resulting figure is as follows:

And that’s it.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list