Plotly treemap:更改级别颜色

Plotly treemap: change level color

我有一个多层次的树状图,是我使用以下简单代码创建的:

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

输出如图:

我想更改特定级别的背景颜色和字体颜色 (例如:层次结构中的第 4 级、最后一级等)。 我该怎么做?

如果你有这个数据:

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")

现在,要为最后一层着色并更改字体颜色,请使用以下代码:

    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()