Amit V
Amit V

Reputation: 301

Plotly treemap: change level color

I have a treemap whit multiple levels, which I created using this simple code:

 fig =px.treemap(
        df,
        path = df.columns,
        color=df['C_2'],
    )

The output is shown in the picture: enter image description here

I'd like to change the background color and the font color for a specific level (for example: level 4 in the hierarchy, last level, etc.). How can I do it?

Upvotes: 2

Views: 4240

Answers (1)

Hamzah Al-Qadasi
Hamzah Al-Qadasi

Reputation: 9786

If you have this data:

import plotly.express as px
import pandas as pd
vendors = ["A", "B", "C", "D", None, "E", "F", "G", "H", None]
sectors = ["Tech", "Tech", "Finance", "Finance", "Other",
           "Tech", "Tech", "Finance", "Finance", "Other"]
regions = ["North", "North", "North", "North", "North",
           "South", "South", "South", "South", "South"]
sales = [1, 3, 2, 4, 1, 2, 2, 1, 4, 1]
df = pd.DataFrame(
    dict(vendors=vendors, sectors=sectors, regions=regions, sales=sales)
)
df["all"] = "all" # in order to have a single root node
fig = px.treemap(df, path=['all', 'regions', 'sectors', 'vendors'], values='sales')
fig.update_traces(root_color="lightgrey")
fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))
fig.show("notebook")

enter image description here

Now, to color the last level and change the font color, use this code below:

    level = 4 # write the number of the last level you have
    lvl_clr = "lightblue"
    font_clr = "blue"

    fig.data[0]['marker']['colors'] =
              [lvl_clr for sector in fig.data[0]['ids'] if len(sector.split("/")) == level]
    fig.data[0]['textfont']['color'] = 
               [font_clr  for sector in fig.data[0]['ids'] if len(sector.split("/")) == level]
    fig.show()  
             
                  

enter image description here

Upvotes: 2

Related Questions