Skip to content

[BUG]: categoryorder 'median ascending' sorts values as strings #8166

Open

Description

@G26karthik

Description

With categoryorder: 'median ascending', some categories get the wrong position on the axis. Lib.median in src/lib/stats.js sorts with data.slice().sort() and no comparator. JavaScript then compares the values as strings. So Lib.median([1, 10, 2]) returns 10, not 2, and Lib.median([-1, -5, 2]) returns -5, not -1.

The median() tests in lib_test.js use only single-digit positive values. String order and numeric order agree for those values, so the tests pass.

Screenshots/Video

No screenshot. The steps below show the order on the axis.

Steps to reproduce

Plotly.newPlot(gd, [{
    x: ['a', 'a', 'a', 'b', 'b', 'b'],
    y: [1, 10, 2, 3, 3, 3]
}], {
    xaxis: {type: 'category', categoryorder: 'median ascending'}
});
  • The median of a is 2. The median of b is 3.
  • Expected axis order: a, b.
  • Actual axis order: b, a, because the median of a comes out as 10.

Notes

A numeric comparator in Lib.median fixes it: data.slice().sort((x, y) => x - y). The only caller of Lib.median is the median aggregation for categoryorder in src/plots/plots.js. Box and violin traces compute their quartiles separately. I can send a PR with this change, a test case in lib_test.js and a draftlog entry.

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions