Skip to content

Commit 06102aa

Browse files
committed
Fix px scrambling categorical axis order when data is split into traces
1 parent 3f8a650 commit 06102aa

3 files changed

Lines changed: 64 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).
1717
- Fix Plotly Express mutating lists passed to the `x` or `y` arguments in wide mode [[#5727](https://github.com/plotly/plotly.py/pull/5727)], with thanks to @cpruijsen for the contribution!
1818
- Fix `px.sunburst`, `px.treemap` and `px.icicle` listing sectors in a different order on every run when `path` is used with a Polars DataFrame; sectors now follow their order of first appearance for all dataframe backends [[#5766](https://github.com/plotly/plotly.py/pull/5766)], with thanks to @Irahan2 for the contribution!
1919
- Fix `mpl_to_plotly` conversion of matplotlib contour lines and line collections: close contour rings ending with `Z` codes, support dash styles, convert date x-axes, separate disjoint subpaths with `None` separators, hide line collection traces from the legend by default, and group consecutive same-style lines into single traces [[#5770](https://github.com/plotly/plotly.py/pull/5770)], with thanks to @robertoffmoura for the contribution!
20+
- Fix Plotly Express scrambling the order of categorical axes when the data is split into several traces (e.g. by `color`); the axis now follows the order of first appearance in the underlying data [[#3198](https://github.com/plotly/plotly.py/issues/3198), [#3291](https://github.com/plotly/plotly.py/issues/3291)]
2021

2122
## [7.1.0] - 2026-09-15
2223

‎plotly/express/_core.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2530,6 +2530,36 @@ def get_groups_and_orders(args, grouper):
25302530
return groups, orders
25312531

25322532

2533+
def _default_category_orders_for_axes(args, groups, orders):
2534+
"""
2535+
Add data-appearance orders for categorical x/y columns.
2536+
2537+
When the data is split into several traces (e.g. by `color`), plotly.js
2538+
orders categories by first appearance across traces, which can differ from
2539+
the order in the underlying data. Recording the data-appearance order here
2540+
lets `set_cartesian_axis_opts` emit an explicit `categoryarray`, matching
2541+
the documented behavior that Plotly Express lays out categorical data in
2542+
the order in which it appears in the data. See #3198.
2543+
"""
2544+
if len(groups) <= 1:
2545+
return orders
2546+
df = args["data_frame"]
2547+
for letter in ("x", "y"):
2548+
col = args.get(letter)
2549+
if not isinstance(col, str) or col in orders or col not in df.columns:
2550+
continue
2551+
uniques = df.get_column(col).unique(maintain_order=True).to_list()
2552+
categories = [
2553+
value
2554+
for value in uniques
2555+
if value is not None
2556+
and not (isinstance(value, float) and math.isnan(value))
2557+
]
2558+
if categories and all(isinstance(value, str) for value in categories):
2559+
orders[col] = categories
2560+
return orders
2561+
2562+
25332563
def make_figure(args, constructor, trace_patch=None, layout_patch=None):
25342564
trace_patch = trace_patch or {}
25352565
layout_patch = layout_patch or {}
@@ -2556,6 +2586,7 @@ def make_figure(args, constructor, trace_patch=None, layout_patch=None):
25562586
)
25572587
grouper = [x.grouper or one_group for x in grouped_mappings] or [one_group]
25582588
groups, orders = get_groups_and_orders(args, grouper)
2589+
orders = _default_category_orders_for_axes(args, groups, orders)
25592590

25602591
col_labels = []
25612592
row_labels = []

‎tests/test_optional/test_px/test_px.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,38 @@ def test_category_order_with_category_as_x(backend):
361361
assert set(trace["x"]) == {"Thur", "Fri", "Sat", "Sun"}
362362

363363

364+
def test_category_order_defaults_to_data_order_with_color():
365+
# https://github.com/plotly/plotly.py/issues/3198
366+
# Splitting into one trace per color must not change the axis order:
367+
# it should follow first appearance in the underlying data.
368+
fig = px.line(
369+
x=["A", "B", None, "B", "C", None, "C", "D", None, "D", "E", None],
370+
y=[1, 1, None, 2, 2, None, 3, 3, None, 4, 4, None],
371+
color=[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1],
372+
)
373+
assert fig["layout"]["xaxis"]["categoryorder"] == "array"
374+
assert fig["layout"]["xaxis"]["categoryarray"] == ("A", "B", "C", "D", "E")
375+
376+
377+
def test_category_order_defaults_to_data_order_with_color_bar():
378+
# https://github.com/plotly/plotly.py/issues/3291
379+
df = pd.DataFrame(
380+
{"x": ["a", "b", "c", "d"], "y": [1, 2, 3, 4], "z": ["p", "q", "p", "q"]}
381+
)
382+
fig = px.bar(df, x="x", y="y", color="z")
383+
assert fig["layout"]["xaxis"]["categoryorder"] == "array"
384+
assert fig["layout"]["xaxis"]["categoryarray"] == ("a", "b", "c", "d")
385+
386+
387+
def test_no_default_category_array_for_single_trace_or_numeric():
388+
# A single trace already follows data order, and numeric axes
389+
# must never get a category array.
390+
fig = px.line(x=["A", "B", "C"], y=[1, 2, 3])
391+
assert fig["layout"]["xaxis"]["categoryorder"] is None
392+
fig = px.line(x=[1, 2, 3], y=[1, 2, 3], color=["a", "b", "a"])
393+
assert fig["layout"]["xaxis"]["categoryorder"] is None
394+
395+
364396
def test_permissive_defaults():
365397
msg = "'PxDefaults' object has no attribute 'should_not_work'"
366398
with pytest.raises(AttributeError, match=msg):

0 commit comments

Comments
 (0)