Skip to content

Fix px hierarchy charts with a categorical color column - #5901

Open
Avalon2222 wants to merge 2 commits into
plotly:mainfrom
Avalon2222:fix-hierarchy-categorical-color
Open

Avalon2222 wants to merge 2 commits into
plotly:mainfrom
Avalon2222:fix-hierarchy-categorical-color

Conversation

@Avalon2222

Copy link
Copy Markdown

Link to issue

No existing issue, the bug and a reproduction are below.

Description of change

px.sunburst, px.treemap and px.icicle fail when path is used and color is a categorical column (pandas category, Polars Enum, PyArrow dictionary). This worked in plotly 5.24.1 and is broken in 7.1.0. In process_dataframe_hierarchy, discrete colors are aggregated with max() and mixed parents get "(?)". max() is not defined for an unordered categorical, and "(?)" is not one of the categories, so both steps fail. This PR casts a categorical or enum color column to string before the group_by, so the figure is the same as with a plain string column.

import pandas as pd
import plotly.express as px

df = pd.DataFrame(
    dict(
        region=["North", "North", "South", "South"],
        vendor=["A", "B", "C", "D"],
        sector=["Tech", "Tech", "Finance", "Tech"],
        sales=[1, 2, 3, 4],
    )
)
df["sector"] = df["sector"].astype("category")
px.sunburst(df, path=["region", "vendor"], values="sales", color="sector")
# before: TypeError: Cannot perform max with non-ordered Categorical

Other backends failed with Cannot setitem on a Categorical with a new category (ordered pandas categorical), conversion from str to enum failed ... ["(?)"] (Polars Enum) and Function 'hash_min_max' has no kernel matching input types (dictionary<...>) (PyArrow).

Testing strategy

Added test_sunburst_treemap_with_path_categorical_color, which runs for every dataframe constructor and for sunburst, treemap and icicle, and checks that the ids and colors match the plain string column. Also added test_sunburst_treemap_with_path_enum_color for Polars Enum. The new tests fail without the change. tests/test_optional/test_px passes locally (1251 passed, 13 skipped, 4 xfailed).

Additional information (optional)

I used an AI coding assistant to help write and test this change, and I reviewed it myself.

Guidelines

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant