Skip to content

Fix Express legend groups with duplicate labels - #5855

Open
Alex-ardashev wants to merge 1 commit into
plotly:mainfrom
Alex-ardashev:fix/express-legend-label-collisions
Open

Alex-ardashev wants to merge 1 commit into
plotly:mainfrom
Alex-ardashev:fix/express-legend-label-collisions

Conversation

@Alex-ardashev

Copy link
Copy Markdown

Link to issue

Related to #2562: this fixes the legend case described in the issue discussion. The separate hover-label collision remains outside this patch.

Description of change

When different grouping columns share a display label, Plotly Express overwrites one column in the legend-name mapping. This drops group values from trace names, hides legend entries, and gives distinct groups the same legend control. Key the mapping by the source column and apply display labels when building the legend title.

Demo

import plotly.express as px

fig = px.scatter(
    {"x": [1, 2, 3, 4], "y": [4, 3, 2, 1],
     "color": ["A", "A", "B", "B"], "symbol": ["one", "two", "one", "two"]},
    x="x", y="y", color="color", symbol="symbol",
    labels={"color": "Group", "symbol": "Group"},
)
print([(trace.name, trace.showlegend) for trace in fig.data])

Before: [('one', True), ('two', True), ('one', False), ('two', False)]

After: [('A, one', True), ('A, two', True), ('B, one', True), ('B, two', True)]

The exported PNG was also checked: it shows all four legend entries with their correct colors and symbols.

Testing strategy

Ten regression cases fail before the fix and pass after it, across pandas (including nullable and Arrow-backed columns), Polars, and PyArrow. Five control cases keep a single legend dimension when color and symbol use the same source column.

pytest tests/test_optional/test_px/test_px.py tests/test_optional/test_px/test_facets.py tests/test_optional/test_px/test_px_hover.py tests/test_optional/test_px/test_marginals.py -q: 540 passed. Ruff lint and formatting pass on both changed Python files. The repository-wide Ruff check reports 1,911 findings, all in unchanged files.

Additional information (optional)

Prepared and tested with OpenAI Codex (GPT-6) at Alex-ardashev's request.

Guidelines

  • I have reviewed the pull request guidelines and Code of Conduct and confirm that this PR follows them.
  • I have added a changelog entry.

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