Skip to content

Plotly Express error with subset categorical pandas column  #4274

Closed
@kvanderwijst

Description

@kvanderwijst

Plotly Express gives a KeyError when using a subselection of a dataframe with a categorical column. The categorical column is useful for custom ordering of values, but sometimes you only want to plot a subset of that dataframe. When not all the values of the Categorical column are present in the subselection, Plotly Express gives an error:

df = pd.DataFrame({
    "x": [0, 0, 1, 0, 1],
    "Value": [10, 5, 7, 3, 8],
    "Category": pd.Categorical(["one", "two", "one", "three", "three"], categories=["one", "two", "three"], ordered=True)
})

px.scatter(
    df[df["Category"].isin(["one", "three"])],  # Works fine with just `df` here
    x="x",
    y="Value",
    color="Category"
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions